Programs & Examples On #Writeonly

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(! {
    QMessageBox::information(0, "error", file.errorString());

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    


C++ cast to derived class

You can't cast a base object to a derived type - it isn't of that type.

If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:

DerivedType D;
BaseType B;

BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type

DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL

How to create an HTTPS server in Node.js?

I found following example.

This works for node v0.1.94 - v0.3.1. server.setSecure() is removed in newer versions of node.

Directly from that source:

const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');

var server = http.createServer();
server.addListener("request", handler);

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

How to select rows for a specific date, ignoring time in SQL Server

You can remove the time component when comparing:

FROM sales 

Another approach is to change the select to cover all the time between the start and end of the date:

FROM sales 
-- WHERE salesDate BETWEEN '11/11/2010 00:00:00.00' AND '11/11/2010 23:59:59.999'
WHERE salesDate BETWEEN '2020-05-18T00:00:00.00' AND '2020-05-18T23:59:59.999'

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
public class StaticResourceConfiguration implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");

            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.


android get real path by Uri.getPath()

Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly. I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as


while if user select gallery from sliding drawer instead of recent then we will get uri as


So I have handle it in getRealPathFromURI_API19()

public static String getRealPathFromURI_API19(Context context, Uri uri) {
        String filePath = "";
        if (uri.getHost().contains("")) {
            // Image pick from recent 
            String wholeID = DocumentsContract.getDocumentId(uri);

            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];

            String[] column = {MediaStore.Images.Media.DATA};

            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";

            Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[]{id}, null);

            int columnIndex = cursor.getColumnIndex(column[0]);

            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            return filePath;
        } else {
            // image pick from gallery 
           return  getRealPathFromURI_BelowAPI11(context,uri)


EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question

EDIT2 Here is complete code with handling virtual files and host other than I have tested this method with content://

How to trigger a file download when clicking an HTML button or JavaScript

If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.

const download = document.getElementById("fileRequest");_x000D_
download.addEventListener('click', request);_x000D_
function request() {_x000D_
    window.location = 'document.docx';_x000D_
.dwnld-cta {_x000D_
    border-radius: 15px 15px;_x000D_
    width: 100px;_x000D_
    line-height: 22px_x000D_
<h1>Download File</h1>_x000D_
<button id="fileRequest" class="dwnld-cta">Download</button>

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;

    public void addBack(ItemInfo info) {
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail = node;

    public void addFront(ItemInfo info) {
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            result =;
            if (tail.prev != null) {
       = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
        return result;

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            result =;
            if ( != null) {
       = null;
                head =;
            } else {
                head = null;
                tail = null;
        return result;

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
   = info;
   = next;
            this.prev = prev;

        public void setInfo(ItemInfo info) {
   = info;

        public void setNext(ItemInfoNode node) {
            next = node;

        public void setPrev(ItemInfoNode node) {
            prev = node;

        public ItemInfo getInfo() {
            return info;

        public ItemInfoNode getNext() {
            return next;

        public ItemInfoNode getPrev() {
            return prev;


Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) { = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getRfdNumber() {
        return rfdNumber;

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;

    public double getPrice() {
        return price;

    public void setPrice(double price) {
        this.price = price;

    public String getOriginalPosition() {
        return originalPosition;

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    while (list.size() > 0){

Jenkins restrict view of jobs per user

Only one plugin help me: Role-Based Strategy :

But official documentation ( is deficient.

The following configurations worked for me:


Basically you just need to create roles and match them with job names using regex.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("&saddr=");// from
    urlString.append("&daddr=");// to
    return urlString.toString();

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code


class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
    protected void onUiEngineAttached(boolean attached) {
        if (attached) {
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection);
            is = urlConnection.openInputStream();
        } catch (IOException e) {
        return is;

See full code on J2MEMapRouteBlackBerryEx on Google Code


Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    public void onCreate(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(;
        new Thread() {
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(;
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        return is;
    protected boolean isRouteDisplayed() {
        return false;

See full code on J2MEMapRouteAndroidEx on Google Code

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date

    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date

    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)

    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    UNIQUE (StudentID, ClassID)

Custom CSS for <audio> tag?

There are CSS options for the audio tag.

Like: html 5 audio tag width

But if you play around with it you'll see results can be unexpected - as of August 2012.

jQuery - trapping tab select event

From what I can tell, per the documentation here:, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div> element, with a <ul> or possibly <ol> element representing the tabs, and then an element for each tab page (presumable a <div> or <p>, possibly a <section> if we're using HTML5). Then you call $().tabs() on the main <div>, not the <ul> element.

After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Can I set text box to readonly when using Html.TextBoxFor?

By setting readonly attribute to either true or false is not going to work in most browsers, I have done it as below, when the mode of the page is "reload", I've not included "readonly" attribute.

@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @readonly = moduleEditModel.Content.ReadOnly, @style = "width:99%; height:360px;" })
@if (Model.Mode.Equals("reload")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @style = "width:99%; height:360px;" })}

Android: How do bluetooth UUIDs work?

To sum up: UUid is used to uniquely identify applications. Each application has a unique UUid

So, use the same UUid for each device

Why does this "Slow network detected..." log appear in Chrome?

I faced same issue for chrome build 61.0.3163.100 on MacOs Sierra with localhost as server. Chrome started logging this message when I changed network speed configuration to 3G fast/ 3G slow and again back to Online.

Fix: When I tried selecting Offline mode and again Online mode, the logging issue disappeared. (This fix may no work on some devices or versions)

Update on 30th Jan 2018

I updated google chrome to Version 64.0.3282.119 (Official Build) (64-bit), it seems this bug is fixed now.

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I had the same problem, I changed my Eclipse project view from Package explorer to Project Explorer.

jQuery hyperlinks - href value?

Why use a <a href>? I solve it like this:

<span class='a'>fake link</span>

And style it with:

.a {text-decoration:underline; cursor:pointer;}

You can easily access it with jQuery:


MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;

  OPEN cur1;

    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;

  CLOSE cur1;

  -- now trim off the trailing , if desired

Skip to next iteration in loop vba

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

Import and Export Excel - What is the best library?

I'm going to throw my hand in for flat csv files, if only because you've got the greatest control over the code. Just make sure that you read in the rows and process them one at a time (reading the document to the end and splitting will eat up all of your memory - same with writing, stream it out).

Yes, the user will have to save-as CSV in excel before you can process it, but perhaps this limitation can be overcome by training and providing clear instructions on the page?

Finally, when you export to the customer, if you set the mime type to text/csv, Excel is usually mapped to that type so it appears to the user to be 'an Excel file'.

How to concatenate a std::string and an int?

Common Answer: itoa()

This is bad. itoa is non-standard, as pointed out here.

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.

Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from

Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.


I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How to load html string in a webview?

I had the same requirement and I have done this in following way.You also can try out this..

Use loadData method

web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

movDirector movProducer like all are my string variable.

In short i retain custom styling for my url.

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:


This will match \d instead of a numeric character

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;

jsFiddle example

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

from   person p
where  instr(,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

react native get TextInput value

The quick and less optimized way to do this is by using arrow function inside your onChangeText callback, by passing username as your argument in your onChangeText callback.

    ref= {(el) => { this.username = el; }}
    onChangeText={(username) => this.setState({username})}

then in your _handlePress method

_handlePress(event) {
    let username=this.state.username;

But this has several drawback!!!

  1. On every render of this component a new arrow function is created.
  2. If the child component is a PureComponent it will force re-renders unnecessarily, this causes huge performance issue especially when dealing with large lists, table, or component iterated over large numbers. More on this in React Docs

Best practice is to use a handler like handleInputChange and bind ```this`` in the constructor.

constructor(props) {
  this.handleChange= this.handleChange.bind(this);

handleChange(event = {}) {
  const name = &&;
  const value = &&;

  this.setState([name]: value);

render() {


Or if you are using es6 class property shorthand which autobinds this. But this has drawbacks, when it comes to testing and performance. Read More Here

handleChange= (event = {}) => {
  const name = &&;
  const value = &&;

  this.setState([name]: value);

render() {


Is there a label/goto in Python?

Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a)
    if (a == 1)
        goto label1;
    if (a == 2)
        goto label2;


Could be done in python like this:

def func1():

def func2():

funcmap = {1 : func1, 2 : func2}

def somefunc(a):
    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.


Your best bet is to either enclose it in a function or use an exception. For the function:

def loopfunc():
    while 1:
        while 1:
            if condition:

For the exception:

    while 1:
        while 1:
            raise BreakoutException #Not a real exception, invent your own
except BreakoutException:

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)

How to make a edittext box in a dialog

Try below code:


 final EditText input = new EditText(context);


How to add an element to a list?

I would do this:


so simply you are adding an object to the list that is present in "data"

How to compare two colors for similarity/difference

I've tried various methods like LAB color space, HSV comparisons and I've found that luminosity works pretty well for this purpose.

Here is Python version

def lum(c):
    def factor(component):
        component = component / 255;
        if (component <= 0.03928):
            component = component / 12.92;
            component = math.pow(((component + 0.055) / 1.055), 2.4);

        return component
    components = [factor(ci) for ci in c]

    return (components[0] * 0.2126 + components[1] * 0.7152 + components[2] * 0.0722) + 0.05;

def color_distance(c1, c2):

    l1 = lum(c1)
    l2 = lum(c2)
    higher = max(l1, l2)
    lower = min(l1, l2)

    return (higher - lower) / higher

c1 = ImageColor.getrgb('white')
c2 = ImageColor.getrgb('yellow')
print(color_distance(c1, c2))

Will give you


Babel 6 regeneratorRuntime is not defined

I get this error using gulp with rollup when I tried to use ES6 generators:

gulp.task('scripts', () => {
  return rollup({
    entry: './app/scripts/main.js',
    format: "iife",
    sourceMap: true,
    plugins: [babel({
      exclude: 'node_modules/**',
      "presets": [
      "plugins": [
      include: {},
      paths: ['./app/scripts'],
      external: [],
      extensions: ['.js']

    loadMaps: true
  .pipe(reload({ stream: true }));

I may case the solution was to include babel-polyfill as bower component:

bower install babel-polyfill --save

and add it as dependency in index.html:

<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources

Check if table exists without using "select from"

SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')

if you get a non-zero count, the table exists.

Crystal Reports 13 And Asp.Net 3.5

I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:

  1. Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.

  2. You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to (for 64 bit machine) or (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS

  3. Make sure you setup FULL TRUST permission on your root folder

  4. The LOCAL SERVICE permission must be setup on your application pool

  5. Make sure the aspnet_client folder exists on your root folder.

If you can make sure all the 5 points above, your Crystal Report should work without any fuss.

Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to, who provides Crystal Report support.

Good luck!

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

What is the correct way to do a CSS Wrapper?

Most basic example (live example here):


    #wrapper {
        width: 500px;
        margin: 0 auto;


        <div id="wrapper">
            Piece of text inside a 500px width div centered on the page

How the principle works:

Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto; or margin-left: auto; margin-right: auto;. The automatic margins make sure your element is centered.

PHP + curl, HTTP POST sample code?

If you try to login on site with cookies.

This code:

if ($server_output == "OK") { ... } else { ... }

May not works if you try to login, because many sites returns status 200, but the post is not successful.

Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.

Also the post can be successful, but the status can be redirect instead 200.

To be sure the post is successful try this:

Follow location after the post, so it will go to the page where the post do redirect to:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

And than check if new cookies existing in the request:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }

In Chart.js set chart title, name of x axis and y axis?

If you have already set labels for your axis like how @andyhasit and @Marcus mentioned, and would like to change it at a later time, then you can try this:

chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";

Full config for reference:

var chartConfig = {
    type: 'line',
    data: {
      datasets: [ {
        label: 'DefaultLabel',
        backgroundColor: '#ff0000',
        borderColor: '#ff0000',
        fill: false,
        data: [],
      } ]
    options: {
      responsive: true,
      scales: {
        xAxes: [ {
          type: 'time',
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Date'
          ticks: {
            major: {
              fontStyle: 'bold',
              fontColor: '#FF0000'
        } ],
        yAxes: [ {
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'value'
        } ]

fill an array in C#

int[] arr = Enumerable.Repeat(42, 10000).ToArray();

I believe that this does the job :)

Installing specific laravel version with composer create-project

To install specific version of laravel try this & simply command on terminal

composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).

That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
    <div>this is an example div &amp; holds an xmp tag:<br />
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
    <p>hello world !!</p>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    This line is also part of the snippet

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<p>a paragraph</p>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<p>a paragraph</p>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<p>a paragraph</p>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

Remove a string from the beginning of a string

Remove www. from beginning of string, this is the easiest way (ltrim)

echo ltrim($a, "www.");

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

sql server #region

BEGIN...END works, you just have to add a commented section. The easiest way to do this is to add a section name! Another route is to add a comment block. See below:

BEGIN  -- Section Name
Comment block some stuff  --end comment should be on next line

 --Very long query

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

It works for me.

git remote add origin
git push origin master

add the repository URL to the origin in the local working directory

Eclipse "this compilation unit is not on the build path of a java project"

I might be picking up the wrong things from so many comments, but if you are using Maven, then are you doing the usual command prompt build and clean?

Go to cmd, navigate to your workspace (usually c:/workspace). Then run "mvn clean install -DskipTests"

After that run "mvn eclipse:eclipse eclipse:clean" (don't need to worry about piping).

Also, do you have any module dependencies in your projects?

If so, try removing the dependencies clicking apply, then readding the dependencies. As this can set eclipse right when it get's confused with buildpath sometimes.

Hope this helps!

How can I temporarily disable a foreign key constraint in MySQL?

It's not a good idea to set a foreign key constraint to 0, because if you do, your database would not ensure it is not violating referential integrity. This could lead to inaccurate, misleading, or incomplete data.

You make a foreign key for a reason: because all the values in the child column shall be the same as a value in the parent column. If there are no foreign key constraints, a child row can have a value that is not in the parent row, which would lead to inaccurate data.

For instance, let's say you have a website for students to login and every student must register for an account as a user. You have one table for user ids, with user id as a primary key; and another table for student accounts, with student id as a column. Since every student must have a user id, it would make sense to make the student id from the student accounts table a foreign key that references the primary key user id in the user ids table. If there are no foreign key checks, a student could end up having a student id and no user id, which means a student can get an account without being a user, which is wrong.

Imagine if it happens to a large amount of data. That's why you need the foreign key check.

It's best to figure out what is causing the error. Most likely, you are trying to delete from a parent row without deleting from a child row. Try deleting from the child row before deleting from the parent row.

Disable dragging an image from an HTML page

You can like this...

document.getElementById('my-image').ondragstart = function() { return false; };

See it working (or not working, rather)

It seems you are using jQuery.

$('img').on('dragstart', function(event) { event.preventDefault(); });

TypeScript sorting an array

The easiest way seems to be subtracting the second number from the first:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);

Insert php variable in a href

Try using printf function or the concatination operator

Error: "setFile(null,false) call failed" when using log4j

if it is window7(like mine), without administrative rights cannot write a file at C: drive

just give another folder in file

Set the name of the file

log4j.appender.FILE.File=C:\server\log.out you can see with notepad++

Where Is Machine.Config?

You can run this in powershell: copy & paste in power shell [System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile

mine output is: C:\Windows\Microsoft.NET\Framework\v2.0.50527\config\machine.config

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you.

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

Solving a "communications link failure" with JDBC and MySQL

In my case it was an idle timeout, that caused the connection to be dropped on the server. The connection was kept open, but not used for a long period of time. Then a client restart works, while I believe a reconnect will work as well.

A not bad solution is to have a daemon/service to ping the connection from time to time.

How do I get the current date and time in PHP?

echo date('y-m-d'); // Today

This will return today's date.

Close Current Tab

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with you can close it with window.close().

Get safe area inset top and bottom heights

For those of you who change to landscape mode, you gotta make sure to use viewSafeAreaInsetsDidChange after the rotation to get the most updated values:

private var safeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

override func viewSafeAreaInsetsDidChange() {
        if #available(iOS 11.0, *) {
            safeAreaInsets = UIApplication.shared.keyWindow!.safeAreaInsets

How can I autoplay a video using the new embed code style for Youtube?

You are using a wrong url for youtube auto play this url display youtube id as wholeJW5meKfy3fY&autoplay=1 which youtube rejects to play. we have to pass autoplay variable to youtube, therefore you have to use ? instead of & so your url will be and your final iframe will be like that.

<iframe src="" width="960" height="447" frameborder="0" allowfullscreen></iframe>

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:

$var = new YourClass();

You can also use the new way to do the same since PHP 5.4:

(new YourClass)->method();

I hope it helps you!

How to configure for SpringJUnit4ClassRunner?

Add a file with at least one appender in root of your classpath.

The contents of the file( can be as simple as


# A1 is set to be a ConsoleAppender.
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n

This will enable log4j logging with default log level as WARN and use the java console to log the messages.

How can I remove the string "\n" from within a Ruby string?

You don't need a regex for this. Use tr:

"some text\nandsomemore".tr("\n","")

What is the best way to call a script from another script?

This is possible in Python 2 using


See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)


However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.

How to run Pip commands from CMD

In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps

On your desktop right click Computer and select Properties

Select Advanced Systems Settings

In popup which you see select Advanced tab and then click Environment Variables

In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.

In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32

Now in my command prompt i moved to above location and gave pip install Flask

enter image description here

How to get item count from DynamoDB?

I'm posting this answer for anyone using C# that wants a fully functional, well-tested answer that demonstrates using query instead of scan. In particular, this answer handles more than 1MB size of items to count.

        public async Task<int> GetAvailableCount(string pool_type, string pool_key)
        var queryRequest = new QueryRequest
            TableName = PoolsDb.TableName,
            ConsistentRead = true,
            Select = Select.COUNT,
            KeyConditionExpression = "pool_type_plus_pool_key = :type_plus_key",
            ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
                {":type_plus_key", new AttributeValue { S =  pool_type + pool_key }}
        var t0 = DateTime.UtcNow;
        var result = await Client.QueryAsync(queryRequest);
        var count = result.Count;
        var iter = 0;
        while ( result.LastEvaluatedKey != null && result.LastEvaluatedKey.Values.Count > 0) 
            var lastkey = result.LastEvaluatedKey.Values.ToList()[0].S;
            _logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} iteration {iter} instance key {lastkey}");
            queryRequest.ExclusiveStartKey = result.LastEvaluatedKey;
            result = await Client.QueryAsync(queryRequest);
            count += result.Count;
        _logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} returned {count} after {iter} iterations in {(DateTime.UtcNow - t0).TotalMilliseconds} ms.");
        return count;

Java 256-bit AES Password-Based Encryption

Use this class for encryption. It works.

public class ObjectCrypter {

    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
            throws NoSuchAlgorithmException,
            BadPaddingException, IOException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(mes);


    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
            throws NoSuchAlgorithmException,
            BadPaddingException, IOException, ClassNotFoundException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(bytes);


And these are ivBytes and a random key;

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");

append multiple values for one key in a dictionary

If you want a (almost) one-liner:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

Using dict.setdefault, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d.

This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality


is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  

How do I get the row count of a Pandas DataFrame?

For dataframe df, a printed comma formatted row count used while exploring data:

def nrow(df):



How to remove all event handlers from an event

You guys are making this WAY too hard on yourselves. It's this easy:

void OnFormClosing(object sender, FormClosingEventArgs e)
    foreach(Delegate d in FindClicked.GetInvocationList())
        FindClicked -= (FindClickedHandler)d;

Auto-loading lib files in Rails 4

I think this may solve your problem:

  1. in config/application.rb:

    config.autoload_paths << Rails.root.join('lib')

    and keep the right naming convention in lib.

    in lib/foo.rb:

    class Foo

    in lib/foo/bar.rb:

    class Foo::Bar
  2. if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:

    in config/initializers/require.rb:

    require "#{Rails.root}/lib/extensions" 


jQuery access input hidden value

If you have an HiddenField you need to:

To access HiddenField Value:

$('#<%=HF.ClientID%>').val()  // HF = your hiddenfield ID

To set HiddenFieldValue

$('#<%=HF.ClientID%>').val('some value')   // HF = your hiddenfield ID

close fxml window by code, javafx

finally, I found a solution

 Window window =   ((Node)(event.getSource())).getScene().getWindow(); 
            if (window instanceof Stage){
                ((Stage) window).close();

Eclipse error ... cannot be resolved to a type

Project -> Build Path -> Configure Build Path
Select Java Build path on the left menu, and select "Source"
 click on Excluded and then Include(All) and then click OK
    Cause : The issue might because u might have deleted the CLASS files 
 or dependencies on the project

For maven users:

Right click on the project


Update Project

Why doesn't Python have a sign function?

Since cmp has been removed, you can get the same functionality with

def cmp(a, b):
    return (a > b) - (a < b)

def sign(a):
    return (a > 0) - (a < 0)

It works for float, int and even Fraction. In the case of float, notice sign(float("nan")) is zero.

Python doesn't require that comparisons return a boolean, and so coercing the comparisons to bool() protects against allowable, but uncommon implementation:

def sign(a):
    return bool(a > 0) - bool(a < 0)

How to clear text area with a button in html using javascript?

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.

Level 1 annotations: @Entity, @Id, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.

Level 2 annotations: @Table, @Column, @JoinColumn, ... Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.

In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.

To answer the questions: the @OneToMany/mappedBy is nicest because it only uses the annotations from the entity domain. The @oneToMany/@JoinColumn is also fine but it uses an implementation annotation where this is not strictly necessary.

Remove composer

Uninstall composer

To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:

sudo apt-get remove composer

Uninstall composer and it's dependent packages

To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.

sudo apt-get remove --auto-remove composer

Purging composer

If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:

sudo apt-get purge composer

To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:

sudo apt-get purge --auto-remove composer

How to dump a table to console?

I know this question has already been marked as answered, but let me plug my own library here. It's called inspect.lua, and you can find it here:

It's just a single file that you can require from any other file. It returns a function that transforms any Lua value into a human-readable string:

local inspect = require('inspect')

print(inspect({1,2,3})) -- {1, 2, 3}
-- {
--   a = 1
--   b = 2
-- }

It indents subtables properly, and handles "recursive tables" (tables that contain references to themselves) correctly, so it doesn't get into infinite loops. It sorts values in a sensible way. It also prints metatable information.


eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here:

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

If the error message is just

"Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.", then grant the login permission for 'NT AUTHORITY\NETWORK SERVICE'

by using


else if the error message is like

"Cannot open database "Phaeton.mdf" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\NETWORK SERVICE'."

try using


under your "Phaeton" database.

Can a java file have more than one class?

If you want to implement a singleton, that is a class that runs in your program with only one instance in memory throughout the execution of the application, then one of the ways to implement a singleton is to nest a private static class inside a public class. Then the inner private class only instantiates itself when its public method to access the private instance is called.

Check out this wiki article,

The concept takes a while to chew on.

What is a quick way to force CRLF in C# / .NET?

This is a quick way to do that, I mean.

It does not use an expensive regex function. It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.

So the search is done directly in one for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops. In some cases, a larger page size might be more efficient.

public static string NormalizeNewLine(this string val)
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
        char ch = val[i];

        if (ch == '\r')
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
                res[j++] = '\r';
                res[j++] = '\n';
                if (a == page) // Ensure capacity
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;

                res[j++] = '\r';
                res[j++] = '\n';
        else if (ch == '\n')
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
                res[j++] = '\r';
                res[j++] = '\n';
                if (a == page) // Ensure capacity
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;

                res[j++] = '\r';
                res[j++] = '\n';
            res[j++] = ch;

    return new string(res, 0, j);

I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?

If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:


but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Git remote branch deleted, but still it appears in 'branch -a'

In our particular case, we use Stash as our remote Git repository. We tried all the previous answers and nothing was working. We ended up having to do the following:

git branch –D branch-name (delete from local)
git push origin :branch-name (delete from remote)

Then when users went to pull changes, they needed to do the following:

git fetch -p

Cannot create PoolableConnectionFactory

This is the actual cause of the problem:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

You have a database communication link problem. Make sure that your application have network access to your database (and the firewall isn't blocking ports to your database).

How to restart Postgresql


  1. On the top left of the MacOS menu bar you have the Postgres Icon
  2. Click on it this opens a drop down menu
  3. Click on Stop -> than click on start

Getting realtime output using subprocess

Complete solution:

import contextlib
import subprocess

# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
    stream = getattr(proc, stream)
    with contextlib.closing(stream):
        while True:
            out = []
            last =
            # Don't loop forever
            if last == '' and proc.poll() is not None:
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                last =
            out = ''.join(out)
            yield out

def example():
    cmd = ['ls', '-l', '/']
    proc = subprocess.Popen(
        # Make all end-of-lines '\n'
    for line in unbuffered(proc):
        print line


Converting Date and Time To Unix Timestamp

You can use Date.getTime() function, or the Date object itself which when divided returns the time in milliseconds.

var d = new Date();

> 1510329641.84

> 1510329641.84

How do you declare an interface in C++?

In C++11 you can easily avoid inheritance altogether:

struct Interface {
  explicit Interface(SomeType& other)
  : foo([=](){ return other.my_foo(); }), 
    bar([=](){ return other.my_bar(); }), /*...*/ {}
  explicit Interface(SomeOtherType& other)
  : foo([=](){ return other.some_foo(); }), 
    bar([=](){ return other.some_bar(); }), /*...*/ {}
  // you can add more types here...

  // or use a generic constructor:
  template<class T>
  explicit Interface(T& other)
  : foo([=](){ return; }), 
    bar([=](){ return; }), /*...*/ {}

  const std::function<void(std::string)> foo;
  const std::function<void(std::string)> bar;
  // ...

In this case, an Interface has reference semantics, i.e. you have to make sure that the object outlives the interface (it is also possible to make interfaces with value semantics).

These type of interfaces have their pros and cons:

  • They require more memory than inheritance based polymorphism.
  • They are in general faster than inheritance based polymorphism.
  • In those cases in which you know the final type, they are much faster! (some compilers like gcc and clang perform more optimizations in types that do not have/inherit from types with virtual functions).

Finally, inheritance is the root of all evil in complex software design. In Sean Parent's Value Semantics and Concepts-based Polymorphism (highly recommended, better versions of this technique are explained there) the following case is studied:

Say I have an application in which I deal with my shapes polymorphically using the MyShape interface:

struct MyShape { virtual void my_draw() = 0; };
struct Circle : MyShape { void my_draw() { /* ... */ } };
// more shapes: e.g. triangle

In your application, you do the same with different shapes using the YourShape interface:

struct YourShape { virtual void your_draw() = 0; };
struct Square : YourShape { void your_draw() { /* ... */ } };
/// some more shapes here...

Now say you want to use some of the shapes that I've developed in your application. Conceptually, our shapes have the same interface, but to make my shapes work in your application you would need to extend my shapes as follows:

struct Circle : MyShape, YourShape { 
  void my_draw() { /*stays the same*/ };
  void your_draw() { my_draw(); }

First, modifying my shapes might not be possible at all. Furthermore, multiple inheritance leads the road to spaghetti code (imagine a third project comes in that is using the TheirShape interface... what happens if they also call their draw function my_draw ?).

Update: There are a couple of new references about non-inheritance based polymorphism:

How can I get a list of locally installed Python modules?

Here is a python code solution that will return a list of modules installed. One can easily modify the code to include version numbers.

import subprocess
import sys
from pprint import pprint

installed_packages = reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')
installed_packages = installed_packages.split('\r\n')
installed_packages = [pkg.split('==')[0] for pkg in installed_packages if pkg != '']

How can I create database tables from XSD files?

There is a command-line tool called XSD2DB, that generates database from xsd-files, available at sourceforge.

How to use comparison and ' if not' in python?

In this particular case the clearest solution is the S.Lott answer

But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.

Using De Morgan's law ¬(A^B) = ¬Av¬B

not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step


if u0 > u or u >= u0+step:

... in this case the «clear» solution is not more clear :P

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, '' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, '');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Reset C int array to zero : the fastest way?

memset (from <string.h>) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.

memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements

By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm>):

std::fill(myarray, myarray+N, 0);

which may be optimized automatically into a memset; I'm quite sure that it will work as fast as memset for ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.

Batch file to map a drive when the folder name contains spaces

net use f: \\\VFServer"\HQ Publications" /persistent:yes

Note that the first quotation mark goes before the leading \ and the second goes after the end of the folder name.

Facebook share button and custom text

use this function derived from link provided by IJas

function openFbPopUp() {
    var fburl = '';
    var fbimgurl = 'http://';
    var fbtitle = 'Your title';
    var fbsummary = "your description";
    var sharerURL = "[url]=" + encodeURI(fburl) + "&p[images][0]=" + encodeURI(fbimgurl) + "&p[title]=" + encodeURI(fbtitle) + "&p[summary]=" + encodeURI(fbsummary);
    return  false;

Or you can also use the latest FB.ui Function if using FB JavaScript SDK for more controlled callback function.

refer: FB.ui

    function openFbPopUp() {
            method: 'feed',
            name: 'Facebook Dialogs',
            link: '',
            picture: '',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
          function(response) {
            if (response && response.post_id) {
              alert('Post was published.');
            } else {
              alert('Post was not published.');

C# Public Enums in Classes

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit

public class Card

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:


This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

How do I get Maven to use the correct repositories?

By default, Maven will always look in the official Maven repository, which is

When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository but you can configure it by changing the <localRepository> value in your ~/.m2/settings.xml) to find any dependency, plugin or report defined in your pom.xml. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one,

You can configure Maven to avoid this default repository by setting a mirror in your settings.xml file:

        <name>Our mirror for Maven repository</name>

This way, instead of contacting, Maven will contact your entreprise repository (http://the/server in this example).

If you want to add another repository, you can define a new one in your settings.xml file:


You can see the complete settings.xml model here.

Concerning the clean process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:

mvn -o clean 

Can anyone explain what JSONP is, in layman terms?


This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.

JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
};"GET", "somewhere.php", true);

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';


The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.


{ "bar": "baz" }


foo( { "bar": "baz" } );

This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).

Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.

Using jQuery

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

By default jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.

Comparable JSON/JSONP Implementations

The following assumes a response object { "bar" : "baz" }


var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
};"GET", "somewhere.php", true);


function foo(response) {
  document.getElementById("output").innerHTML =;

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';


How to save and load cookies using Python + Selenium WebDriver

This is code I used in Windows. It works.

for item in COOKIES.split(';'):
    name,value = item.split('=', 1)
    name=name.replace(' ', '').replace('\r', '').replace('\n', '')
    value = value.replace(' ', '').replace('\r', '').replace('\n', '')
            "domain": "",  # Google Chrome
            "expires": "",
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False

Is it possible to have empty RequestParam values use the defaultValue?

You can also do something like this -

 @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i

How to test my servlet using JUnit

Updated Feb 2018: OpenBrace Limited has closed down, and its ObMimic product is no longer supported.

Here's another alternative, using OpenBrace's ObMimic library of Servlet API test-doubles (disclosure: I'm its developer).

package com.openbrace.experiments.examplecode.stackoverflow5434419;

import static org.junit.Assert.*;
import com.openbrace.experiments.examplecode.stackoverflow5434419.YourServlet;
import com.openbrace.obmimic.mimic.servlet.ServletConfigMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletRequestMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletResponseMimic;
import com.openbrace.obmimic.substate.servlet.RequestParameters;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * Example tests for {@link YourServlet#doPost(HttpServletRequest,
 * HttpServletResponse)}.
 * @author Mike Kaufman, OpenBrace Limited
public class YourServletTest {

    /** The servlet to be tested by this instance's test. */
    private YourServlet servlet;

    /** The "mimic" request to be used in this instance's test. */
    private HttpServletRequestMimic request;

    /** The "mimic" response to be used in this instance's test. */
    private HttpServletResponseMimic response;

     * Create an initialized servlet and a request and response for this
     * instance's test.
     * @throws ServletException if the servlet's init method throws such an
     *     exception.
    public void setUp() throws ServletException {
         * Note that for the simple servlet and tests involved:
         * - We don't need anything particular in the servlet's ServletConfig.
         * - The ServletContext isn't relevant, so ObMimic can be left to use
         *   its default ServletContext for everything.
        servlet = new YourServlet();
        servlet.init(new ServletConfigMimic());
        request = new HttpServletRequestMimic();
        response = new HttpServletResponseMimic();

     * Test the doPost method with example argument values.
     * @throws ServletException if the servlet throws such an exception.
     * @throws IOException if the servlet throws such an exception.
    public void testYourServletDoPostWithExampleArguments()
            throws ServletException, IOException {

        // Configure the request. In this case, all we need are the three
        // request parameters.
        RequestParameters parameters
            = request.getMimicState().getRequestParameters();
        parameters.set("username", "mike");
        parameters.set("password", "xyz#zyx");
        parameters.set("name", "Mike");

        // Run the "doPost".
        servlet.doPost(request, response);

        // Check the response's Content-Type, Cache-Control header and
        // body content.
        assertEquals("text/html; charset=ISO-8859-1",
        assertArrayEquals(new String[] { "no-cache" },
        assertEquals("...expected result from dataManager.register...",




  • Each "mimic" has a "mimicState" object for its logical state. This provides a clear distinction between the Servlet API methods and the configuration and inspection of the mimic's internal state.

  • You might be surprised that the check of Content-Type includes "charset=ISO-8859-1". However, for the given "doPost" code this is as per the Servlet API Javadoc, and the HttpServletResponse's own getContentType method, and the actual Content-Type header produced on e.g. Glassfish 3. You might not realise this if using normal mock objects and your own expectations of the API's behaviour. In this case it probably doesn't matter, but in more complex cases this is the sort of unanticipated API behaviour that can make a bit of a mockery of mocks!

  • I've used response.getMimicState().getContentType() as the simplest way to check Content-Type and illustrate the above point, but you could indeed check for "text/html" on its own if you wanted (using response.getMimicState().getContentTypeMimeType()). Checking the Content-Type header the same way as for the Cache-Control header also works.

  • For this example the response content is checked as character data (with this using the Writer's encoding). We could also check that the response's Writer was used rather than its OutputStream (using response.getMimicState().isWritingCharacterContent()), but I've taken it that we're only concerned with the resulting output, and don't care what API calls produced it (though that could be checked too...). It's also possible to retrieve the response's body content as bytes, examine the detailed state of the Writer/OutputStream etc.

There are full details of ObMimic and a free download at the OpenBrace website. Or you can contact me if you have any questions (contact details are on the website).

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[email protected]
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.


First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:


How to test an SQL Update statement before running it?

Not a direct answer, but I've seen many borked prod data situations that could have been avoided by typing the WHERE clause first! Sometimes a WHERE 1 = 0 can help with putting a working statement together safely too. And looking at an estimated execution plan, which will estimate rows affected, can be useful. Beyond that, in a transaction that you roll back as others have said.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How to remove the first Item from a list?

There is a data structure called deque or double ended queue which is faster and efficient than a list. You can use your list and convert it to deque and do the required transformations in it. You can also convert the deque back to list.

import collections
mylist = [0, 1, 2, 3, 4]

#make a deque from your list
de = collections.deque(mylist)

#you can remove from a deque from either left side or right side

#you can covert the deque back to list
mylist = list(de)

Deque also provides very useful functions like inserting elements to either side of the list or to any specific index. You can also rotate or reverse a deque. Give it a try!

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

How to convert DateTime? to DateTime

Try this:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

ASP.NET Core Web API Authentication

In this public Github repo you can see a simple example of a ASP.NET Core 2.2 web API with endpoints protected by Basic Authentication.

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

Android, How to create option Menu

import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class AndroidWalkthroughApp2 extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

    public boolean onCreateOptionsMenu(Menu menu) {
        // show menu when menu button is pressed
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // display a message when a button was pressed
        String message = "";
        if (item.getItemId() == {
            message = "You selected option 1!";
        else if (item.getItemId() == {
            message = "You selected option 2!";
        else {
            message = "Why would you select that!?";

        // show message via toast
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);;

        return true;

How to programmatically set the Image source

{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

How do I convert hh:mm:ss.000 to milliseconds in Excel?

try this:


Maybe you need to change semi-colon by coma...

Retrieving a random item from ArrayList

anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.

Might want to re-write it like:

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
    private Random randomGenerator;
    private ArrayList<Item> catalogue;

    public Catalogue()
        catalogue = new ArrayList<Item>();
        randomGenerator = new Random();

    public Item anyItem()
        int index = randomGenerator.nextInt(catalogue.size());
        Item item = catalogue.get(index);
        System.out.println("Managers choice this week" + item + "our recommendation to you");
        return item;

How do I close a tkinter window?

you only need to type this:


and you don't even need the quit() function cause when you set that as commmand it will quit the entire program.

How to apply a function to two columns of Pandas dataframe

A simple solution is:

df['col_3'] = df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)

Formatting a number with exactly two decimals in JavaScript

You could also use the .toPrecision() method and some custom code, and always round up to the nth decimal digit regardless the length of int part.

function glbfrmt (number, decimals, seperator) {
    return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);

You could also make it a plugin for a better use.

How to print_r $_POST array?

$_POST is an array in itsself you don't need to make an array out of it. What you did is nest the $_POST array inside a new array. This is why you print Array. Change it to:

foreach ($_POST as $key => $value) {

  echo "<p>".$key."</p>";
  echo "<p>".$value."</p>";
  echo "<hr />";


Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, ' = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, ' = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here:


Think it should be:

    ->innerJoin('c.phones', 'p', Join::ON, ' = p.customerId')
    ->where('c.username = :username')
    ->andWhere(' = :phone');

        'username' => $username,
        'phone' => $phone->getPhone(),

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Initializing a struct to 0

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:
C and C++ : Partial initialization of automatic structure

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

bool to int: x = (x == 'true') + 0

Now the x contains 1 if x == 'true' else 0.

Note: x == 'true' will return bool which then will be typecasted to int having value (1 if bool value is True else 0) when added with 0.

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
    }                                              // add this line

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

/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
    int result = 0;
    Iterator<Row> rowIterator = xssfSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row =;
        List<Cell> cells = new ArrayList<>();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
        for (int i = cells.size(); i >= 0; i--) {
            Cell cell = cells.get(i-1);
            if (cell.toString().trim().isEmpty()) {
            } else {
                result = cells.size() > result ? cells.size() : result;
    return result;

Check if element exists in jQuery

How do I check if an element exists

if ($("#mydiv").length){  }

If it is 0, it will evaluate to false, anything more than that true.

There is no need for a greater than, less than comparison.

Each GROUP BY expression must contain at least one column that is not an outer reference

Well, as it was said before, you can't GROUP by literals, I think that you are confused cause you can ORDER by 1, 2, 3. When you use functions as your columns, you need to GROUP by the same expression. Besides, the HAVING clause is wrong, you can only use what is in the agreggations. In this case, your query should be like this:

LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),,
MAX(qvalues.rid) MaxRid
FROM batchinfo join qvalues 
ON batchinfo.rowid=qvalues.rowid
WHERE LEN(datapath)>4
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),,

React JS Error: is not defined react/jsx-no-undef

should write like this -->

import Map from './map';

  1. look in this Map should have first later is capital .(important note)
  2. inset the single 'just mention your file location correctly'.

Is Django for the frontend or backend?


Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

How do I include negative decimal numbers in this regular expression?


accepts positive or negative decimal values.

android.widget.Switch - on/off event listener?

My solution, using a SwitchCompat and Kotlin. In my situation, i needed to react to a change only if the user triggered it through the UI. In fact, my switch reacts to a LiveData, and this made both setOnClickListener and setOnCheckedChangeListener unusable. setOnClickListener in fact reacts correctly to user interaction, but it's not triggered if the user drags the thumb across the switch. setOnCheckedChangeListener on the other end is triggered also if the switch is toggled programmatically (for example by an observer). Now in my case the switch was present on two fragments, and so onRestoreInstanceState would trigger in some cases the switch with an old value overwriting the correct value.

So, i looked at the code of SwitchCompat, and was able to mimic it's behaviour successfully in distinguishing click and drag and used that to build a custom touchlistener that works as it should. Here we go:

 * This function calls the lambda function passed with the right value of isChecked
 * when the switch is tapped with single click isChecked is relative to the current position so we pass !isChecked
 * when the switch is dragged instead, the position of the thumb centre where the user leaves the
 * thumb is compared to the middle of the switch, and we assume that left means false, right means true
 * (there is no rtl or vertical switch management)
 * The behaviour is extrapolated from the SwitchCompat source code
class SwitchCompatTouchListener(private val v: SwitchCompat, private val lambda: (Boolean)->Unit) :  View.OnTouchListener {
    companion object {
        private const val TOUCH_MODE_IDLE = 0
        private const val TOUCH_MODE_DOWN = 1
        private const val TOUCH_MODE_DRAGGING = 2

    private val vc = ViewConfiguration.get(v.context)
    private val mScaledTouchSlop = vc.scaledTouchSlop
    private var mTouchMode = 0
    private var mTouchX = 0f
    private var mTouchY = 0f

     * @return true if (x, y) is within the target area of the switch thumb
     * x,y and rect are in view coordinates, 0,0 is top left of the view
    private fun hitThumb(x: Float, y: Float): Boolean {
        val rect = v.thumbDrawable.bounds
        return x >= rect.left && x <= rect.right && y >= && y <= rect.bottom

    override fun onTouch(view: View, event: MotionEvent): Boolean {
        if (view == v) {
            when (MotionEventCompat.getActionMasked(event)) {
                MotionEvent.ACTION_DOWN -> {
                    val x = event.x
                    val y = event.y
                    if (v.isEnabled && hitThumb(x, y)) {
                        mTouchMode = TOUCH_MODE_DOWN;
                        mTouchX = x;
                        mTouchY = y;
                MotionEvent.ACTION_MOVE -> {
                    val x = event.x
                    val y = event.y
                    if (mTouchMode == TOUCH_MODE_DOWN &&
                        (abs(x - mTouchX) > mScaledTouchSlop || abs(y - mTouchY) > mScaledTouchSlop)
                        mTouchMode = TOUCH_MODE_DRAGGING;
                MotionEvent.ACTION_CANCEL -> {
                    if (mTouchMode == TOUCH_MODE_DRAGGING) {
                        val r = v.thumbDrawable.bounds
                        if (r.left + r.right < v.width) lambda(false)
                        else lambda(true)
                    } else lambda(!v.isChecked)
                    mTouchMode = TOUCH_MODE_IDLE;
        return v.onTouchEvent(event)

How to use it:

the actual touch listener that accepts a lambda with the code to execute:

    SwitchCompatTouchListener(myswitch) {
        // here goes all the code for your callback, in my case
        // i called a service which, when successful, in turn would 
        // update my liveData 

For the sake of completeness, this is how the observer for the state switchstate (if you have it) looked like:

switchstate.observe(this, Observer {
    myswitch.isChecked = it

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

A clean if/else conditional shell script:

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

recursively use scp but excluding some folders

Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude.

Something like this should do:

sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store

Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.

MySQL: @variable vs. variable. What's the difference?

MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.

While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.

I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.

MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.

Start / Stop a Windows Service from a non-Administrator user account

I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:

subinacl.exe /service w3svc /grant=VMX001\job=PTO

The permissions you can grant are defined as follows (list taken from here):

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service 
U : Service User-Defined Control Commands

So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.

Can I serve multiple clients using just Flask as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as

Picasso v/s Imageloader v/s Fresco vs Glide

Neither Glide nor Picasso is perfect. The way Glide loads an image to memory and do the caching is better than Picasso which let an image loaded far faster. In addition, it also helps preventing an app from popular OutOfMemoryError. GIF Animation loading is a killing feature provided by Glide. Anyway Picasso decodes an image with better quality than Glide.

Which one do I prefer? Although I use Picasso for such a very long time, I must admit that I now prefer Glide. But I would recommend you to change Bitmap Format to ARGB_8888 and let Glide cache both full-size image and resized one first. The rest would do your job great!

  • Method count of Picasso and Glide are at 840 and 2678 respectively.
  • Picasso (v2.5.1)'s size is around 118KB while Glide (v3.5.2)'s is around 430KB.
  • Glide creates cached images per size while Picasso saves the full image and process it, so on load it shows faster with Glide but uses more memory.
  • Glide use less memory by default with RGB_565.

+1 For Picasso Palette Helper.

There is a post that talk a lot about Picasso vs Glide post

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Change output format for MySQL command line results to CSV

How about using sed? It comes standard with most (all?) Linux OS.

sed 's/\t/<your_field_delimiter>/g'.

This example uses GNU sed (Linux). For POSIX sed (AIX/Solaris)I believe you would type a literal TAB instead of \t

Example (for CSV output):

#mysql mysql -B -e "select * from user" | while read; do sed 's/\t/,/g'; done


Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?


<script src=""></script>
<script src=""></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>


public void PostRawJson(string json)
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;

Make absolute positioned div expand parent div height

Also consider next approach:


.parent {
  height: 100%;
.parent:after {
  content: '';
  display: block;

Also since you are trying to reposition divs consider css grid

What charset does Microsoft Excel use when saving files?

You can create CSV file using encoding UTF8 + BOM (

First three bytes are BOM (0xEF,0xBB,0xBF) and then UTF8 content.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Git - push current branch shortcut

For what it's worth, the ultimate shortcut:

In my .bash_profile I have alias push="git push origin HEAD", so whenever i type push I know I'm pushing to the current branch I'm on.

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

How do I use a C# Class Library in a project?

I'm not certain why everyone is claiming that you need a using statement at the top of your file, as this is entirely unnecessary.

Right-click on the "References" folder in your project and select "Add Reference". If your new class library is a project in the same solution, select the "Project" tab and pick the project. If the new library is NOT in the same solution, click the "Browse" tab and find the .dll for your new project.

Find all elements with a certain attribute value in jquery

Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:


Hope that helps somebody who happens to land on this page looking for the same thing that I was :).

Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):


What is the best way to extract the first word from a string in Java?

None of these answers appears to define what the OP might mean by a "word". As others have already said, a "word boundary" may be a comma, and certainly can't be counted on to be a space, or even "white space" (i.e. also tabs, newlines, etc.)

At the simplest, I'd say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It's a big topic.

But a start might be this (NB written in Groovy):

String givenString = "one two9 thr0ee four"
// String givenString = "onnÜÐæne;:two9===thr0eè? four!"
// String givenString = "mouse"
// String givenString = "&&^^^%"

String[] substrings = givenString.split( '[^\\p{L}^\\d]+' )

println "substrings |$substrings|"

println "first word |${substrings[0]}|"

This works OK for the first, second and third givenStrings. For "&&^^^%" it says that the first "word" is a zero-length string, and the second is "^^^". Actually a leading zero-length token is String.split's way of saying "your given String starts not with a token but a delimiter".

NB in regex \p{L} means "any Unicode letter". The parameter of String.split is of course what defines the "delimiter pattern"... i.e. a clump of characters which separates tokens.

NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.

NB3 My first port of call was Apache Commons' StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out... ... although something of use may be lurking there.

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml

Use PowerShell to Parse an XML File

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler.

AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value.

The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.

Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.

A possible solution is

  • Download Xcode 10.2 from a direkt link (not from App Store).
  • Rename it for example to Xcode102.
  • Put it into /Applications. It's possible to have multiple Xcode versions in the same directory.
  • Create a symbolic link in to have access to the 12.2 device support folder in Xcode 10.2

    ln -s /Applications/\ \(16E226\) /Applications/

You can move Xcode 10.2 to somewhere else but then you have to adjust the path.

Now Xcode 10.1 supports devices running iOS 12.2

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)


plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:


before the show. Yielding:

neater side by side plot

How to copy a file to multiple directories using the gnu cp command

Using a bash script


for (( i=0; i<NumberOfDestinations; i++))
        cp  SourcePath/fileName.ext ${DESTINATIONPATH[$i]}


CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;

This way you can group multiple items to the right(or just one).

How to terminate script execution when debugging in Google Chrome?

One way you can do it is pause the script, look at what code follows where you are currently stopped, e.g.:

var something = somethingElse.blah;

In the console, do the following:

delete somethingElse;

Then play the script: it will cause a fatal error when it tries to access somethingElse, and the script will die. Voila, you've terminated the script.

EDIT: Originally, I deleted a variable. That's not good enough. You have to delete a function or an object of which JavaScript attempts to access a property.

Where do I find some good examples for DDD?

ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.

Updated link:

How to convert View Model into JSON object in ASP.NET MVC?

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

pass post data with window.location.href

Add a form to your HTML, something like this:

<form style="display: none" action="/the/url" method="POST" id="form">
  <input type="hidden" id="var1" name="var1" value=""/>
  <input type="hidden" id="var2" name="var2" value=""/>

and use JQuery to fill these values (of course you can also use javascript to do something similar)


Then finally submit the form


on the server side you should be able to get the data you sent by checking var1 and var2, how to do this depends on what server-side language you are using.

How to listen state changes in react.js?

Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy

Oracle's default date format is YYYY-MM-DD, WHY?

Most of the IDE you can configure the default mask for some kind of data as date, currency, decimal separator, etc.

If your are using Oracle SQL Developer:

Tool > Preferences > Database > NLS

Date Format: YYYY-MM-DD HH24:MI:SS

Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

How can I find an element by CSS class with XPath?

I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago

//div[contains(concat(' ', @class, ' '), ' Test ')]

C++ IDE for Macs

Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.

Clion from JetBrains, also is available now, and uses Cmake as project model.

How to cast int to enum in C++?

Your code

enum Test
    A, B

int a = 1;


Test castEnum = static_cast<Test>(a);

How to insert an item into a key/value pair object?

I would use the Dictionary<TKey, TValue> (so long as each key is unique).

EDIT: Sorry, realised you wanted to add it to a specific position. My bad. You could use a SortedDictionary but this still won't let you insert.

how to convert java string to Date object

var startDate = "06/27/2007";
startDate = new Date(startDate);


Select from table by knowing only date without time (ORACLE)

Try the following way.

Select * from t1 where date(col_name)="8/3/2010" 

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Proper use of const for defining functions in JavaScript

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.


How to specify more spaces for the delimiter using cut?

If you want to pick columns from a ps output, any reason to not use -o?


ps ax -o pid,vsz
ps ax -o pid,cmd

Minimum column width allocated, no padding, only single space field separator.

ps ax --no-headers -o pid:1,vsz:1,cmd

3443 24600 -bash
8419 0 [xfsalloc]
8420 0 [xfs_mru_cache]
8602 489316 /usr/sbin/apache2 -k start
12821 497240 /usr/sbin/apache2 -k start
12824 497132 /usr/sbin/apache2 -k start

Pid and vsz given 10 char width, 1 space field separator.

ps ax --no-headers -o pid:10,vsz:10,cmd

  3443      24600 -bash
  8419          0 [xfsalloc]
  8420          0 [xfs_mru_cache]
  8602     489316 /usr/sbin/apache2 -k start
 12821     497240 /usr/sbin/apache2 -k start
 12824     497132 /usr/sbin/apache2 -k start

Used in a script:-

echo "PID: ${oldpid}"
echo "Command: $(ps -ho cmd ${oldpid})"

Determine the number of lines within a text file

This would use less memory, but probably take longer

int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Add vertical whitespace using Twitter Bootstrap?

In Bootstrap 4 there are spacing utilites.

Citing the documentation for used notation:

Spacing utilities that apply to all breakpoints, from xs to xl, have no breakpoint abbreviation in them. This is because those classes are applied from min-width: 0 and up, and thus are not bound by a media query. The remaining breakpoints, however, do include a breakpoint abbreviation.

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Where property is one of:

  • m - for classes that set margin
  • p - for classes that set padding

Where sides is one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • l - for classes that set margin-left or padding-left
  • r - for classes that set margin-right or padding-right
  • x - for classes that set both *-left and *-right
  • y - for classes that set both *-top and *-bottom
  • blank - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

  • 0 - for classes that eliminate the margin or padding by setting it to 0
  • 1 - (by default) for classes that set the margin or padding to $spacer * .25
  • 2 - (by default) for classes that set the margin or padding to $spacer * .5
  • 3 - (by default) for classes that set the margin or padding to $spacer
  • 4 - (by default) for classes that set the margin or padding to $spacer * 1.5
  • 5 - (by default) for classes that set the margin or padding to $spacer * 3

So to have some extra vertical space above and below an element you would use my-5 class.

How to recover stashed uncommitted changes

git stash pop

will get everything back in place

as suggested in the comments, you can use git stash branch newbranch to apply the stash to a new branch, which is the same as running:

git checkout -b newbranch
git stash pop

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

Using boolean values in C

Anything nonzero is evaluated to true in boolean operations, so you could just

#define TRUE 1
#define FALSE 0

and use the constants.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

In my case. I installed the release-version app. And after uninstall the app from my device. Thing works fine.

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))

jQuery - Trigger event when an element is removed from the DOM

Only jQuery is required (No jQuery UI needed)

(I have extracted this extension from the jQuery UI framework)

Works with: empty() and html() and remove()

$.cleanData = ( function( orig ) {
    return function( elems ) {
        var events, elem, i;
        for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
            try {

                // Only trigger remove when necessary to save time
                events = $._data( elem, "events" );
                if ( events && events.remove ) {
                    $( elem ).triggerHandler( "remove" );

            // Http://
            } catch ( e ) {}
        orig( elems );
} )( $.cleanData );

With this solution you can also unbind the event handler.


Try it! - Example

$.cleanData = (function(orig) {_x000D_
  return function(elems) {_x000D_
    var events, elem, i;_x000D_
    for (i = 0;_x000D_
      (elem = elems[i]) != null; i++) {_x000D_
      try {_x000D_
        // Only trigger remove when necessary to save time_x000D_
        events = $._data(elem, "events");_x000D_
        if (events && events.remove) {_x000D_
        // Http://
      } catch (e) {}_x000D_
$("#DivToBeRemoved").on("remove", function() {_x000D_
  console.log("div was removed event fired");_x000D_
$("p").on("remove", function() {_x000D_
  console.log("p was removed event fired");_x000D_
$("span").on("remove", function() {_x000D_
  console.log("span was removed event fired");_x000D_
// $("span").off("remove");_x000D_
$("#DivToBeRemoved").on("click", function() {_x000D_
  console.log("Div was clicked");_x000D_
function RemoveDiv() {_x000D_
  //       $("#DivToBeRemoved").parent().html("");    _x000D_
<script src=""></script>_x000D_
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>_x000D_
<div class="container">_x000D_
  <button onclick="RemoveDiv();">Click here to remove div below</button>_x000D_
  <div id="DivToBeRemoved">_x000D_
    contains 1 p element _x000D_
    which in turn contains a span element_x000D_
    <p>i am p (within div)_x000D_
      <br><br><span>i am span (within div)</span></p>_x000D_

Additional Demo - jsBin

Should I use SVN or Git?

You have to go with a DVCS, it is like a quantum leap in source management. Personally I use Monotone and its sped up development time no end. We are using it for Windows, Linux and Mac and it has been very stable. I even have buildbot doing nightly builds of the project on each of the platforms.

DVCS while being distributed usually means you will create a central server just for people to push changes to and from.

How to get last 7 days data from current datetime to last 7 days in sql server

To pull data for the last 3 days, not the current date :

date(timestamp) >= curdate() - 3
AND date(timestamp) < curdate()



FROM user_login
WHERE age > 18
AND date(timestamp) >= curdate() - 3
AND date(timestamp) < curdate()


Delay/Wait in a test case of Xcode UI testing

iOS 11 / Xcode 9

<#yourElement#>.waitForExistence(timeout: 5)

This is a great replacement for all the custom implementations on this site!

Be sure to have a look at my answer here: There I describe an alternative to waiting for requests which will greatly reduce the time your tests are running!

Fastest way to download a GitHub project

I agree with the current answers, I just wanna add little more information, Here's a good functionality

if you want to require just zip file but the owner has not prepared a zip file,

To simply download a repository as a zip file: add the extra path /zipball/master/ to the end of the repository URL, This will give you a full ZIP file

For example, here is your repository

Add zipball/master/ in your repository link

Paste the URL into your browser and it will give you a zip file to download

Shorter syntax for casting from a List<X> to a List<Y>?

To add to Sweko's point:

The reason why the cast

var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y

is not possible is because the List<T> is invariant in the Type T and thus it doesn't matter whether X derives from Y) - this is because List<T> is defined as:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces

(Note that in this declaration, type T here has no additional variance modifiers)

However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe derives from Animal:

IEnumerable<Animal> animals = giraffes;

This is because IEnumerable<T> supports covariance in T - this makes sense given that IEnumerable implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out keyword in the declaration of IEnumerable<T>:

public interface IEnumerable<out T> : IEnumerable

(Here's further explanation for the reason why mutable collections like List cannot support covariance, whereas immutable iterators and collections can.)

Casting with .Cast<T>()

As others have mentioned, .Cast<T>() can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach loop).

Filtering and Casting with OfType<T>()

If the input list contains elements of different, incompatable types, the potential InvalidCastException can be avoided by using .OfType<T>() instead of .Cast<T>(). (.OfType<>() checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)


Also note that if the OP had written this instead: (note the explicit Y y in the foreach)

List<Y> ListOfY = new List<Y>();

foreach(Y y in ListOfX)

that the casting will also be attempted. However, if no cast is possible, an InvalidCastException will result.


For example, given the simple (C#6) class hierarchy:

public abstract class Animal
    public string Name { get;  }
    protected Animal(string name) { Name = name; }

public class Elephant :  Animal
    public Elephant(string name) : base(name){}

public class Zebra : Animal
    public Zebra(string name)  : base(name) { }

When working with a collection of mixed types:

var mixedAnimals = new Animal[]
    new Zebra("Zed"),
    new Elephant("Ellie")

foreach(Animal animal in mixedAnimals)
     // Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`

var castedAnimals = mixedAnimals.Cast<Elephant>()
    // Also fails for Zed with `InvalidCastException


var castedAnimals = mixedAnimals.OfType<Elephant>()
// Ellie

filters out only the Elephants - i.e. Zebras are eliminated.

Re: Implicit cast operators

Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.

If we add a conversion operator to convert a Zebra to an Elephant:

public class Zebra : Animal
    public Zebra(string name) : base(name) { }
    public static implicit operator Elephant(Zebra z)
        return new Elephant(z.Name);

Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[] to Elephant[], given that the Zebras can be now converted to a homogeneous collection of Elephants:

var compilerInferredAnimals = new []
    new Zebra("Zed"),
    new Elephant("Ellie")

Using Implicit Conversion Operators at run time

*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic:

var mixedAnimals = new Animal[] // i.e. Polymorphic collection
    new Zebra("Zed"),
    new Elephant("Ellie")

foreach (dynamic animal in mixedAnimals)
// Returns Zed, Ellie

How to remove a web site from google analytics

Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.