Programs & Examples On #Classview

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

Type or namespace name does not exist

Check to see that your target framework has the same .NET versions. I had the same problem and my class .NET was 3.5 and web solution had 4.5. I synchronised those, and then it worked :)

implement addClass and removeClass functionality in angular2

Try to use it via [ngClass] property:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

Mocking Logger and LoggerFactory with PowerMock and Mockito

Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.

Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...

I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.

When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...

Class under test

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClassWithSomeLogging  {

    private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);

    public void doStuff(boolean b) {
        if(b) {
            LOG.info("true");
        } else {
            LOG.info("false");
        }

    }
}

Test

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;


@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {

    private static Logger mockLOG;

    @BeforeClass
    public static void setup() {
        mockStatic(LoggerFactory.class);
        mockLOG = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
    }

    @Test
    public void testIt() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(true);

        verify(mockLOG, times(1)).info("true");
    }

    @Test
    public void testIt2() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(false);

        verify(mockLOG, times(1)).info("false");
    }

    @AfterClass
    public static void verifyStatic() {
        verify(mockLOG, times(1)).info("true");
        verify(mockLOG, times(1)).info("false");
        verify(mockLOG, times(2)).info(anyString());
    }
}

Note

If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true"); - rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....

How to parse the AndroidManifest.xml file inside an .apk package

In case it's useful, here's a C++ version of the Java snippet posted by Ribo:

struct decompressXML
{
    // decompressXML -- Parse the 'compressed' binary form of Android XML docs 
    // such as for AndroidManifest.xml in .apk files
    enum
    {
        endDocTag = 0x00100101,
        startTag =  0x00100102,
        endTag =    0x00100103
    };

    decompressXML(const BYTE* xml, int cb) {
    // Compressed XML file/bytes starts with 24x bytes of data,
    // 9 32 bit words in little endian order (LSB first):
    //   0th word is 03 00 08 00
    //   3rd word SEEMS TO BE:  Offset at then of StringTable
    //   4th word is: Number of strings in string table
    // WARNING: Sometime I indiscriminently display or refer to word in 
    //   little endian storage format, or in integer format (ie MSB first).
    int numbStrings = LEW(xml, cb, 4*4);

    // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
    // of the length/string data in the StringTable.
    int sitOff = 0x24;  // Offset of start of StringIndexTable

    // StringTable, each string is represented with a 16 bit little endian 
    // character count, followed by that number of 16 bit (LE) (Unicode) chars.
    int stOff = sitOff + numbStrings*4;  // StringTable follows StrIndexTable

    // XMLTags, The XML tag tree starts after some unknown content after the
    // StringTable.  There is some unknown data after the StringTable, scan
    // forward from this point to the flag for the start of an XML start tag.
    int xmlTagOff = LEW(xml, cb, 3*4);  // Start from the offset in the 3rd word.
    // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
    for (int ii=xmlTagOff; ii<cb-4; ii+=4) {
      if (LEW(xml, cb, ii) == startTag) { 
        xmlTagOff = ii;  break;
      }
    } // end of hack, scanning for start of first start tag

    // XML tags and attributes:
    // Every XML start and end tag consists of 6 32 bit words:
    //   0th word: 02011000 for startTag and 03011000 for endTag 
    //   1st word: a flag?, like 38000000
    //   2nd word: Line of where this tag appeared in the original source file
    //   3rd word: FFFFFFFF ??
    //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
    //   5th word: StringIndex of Element Name
    //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

    // Start tags (not end tags) contain 3 more words:
    //   6th word: 14001400 meaning?? 
    //   7th word: Number of Attributes that follow this tag(follow word 8th)
    //   8th word: 00000000 meaning??

    // Attributes consist of 5 words: 
    //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
    //   1st word: StringIndex of Attribute Name
    //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
    //   3rd word: Flags?
    //   4th word: str ind of attr value again, or ResourceId of value

    // TMP, dump string table to tr for debugging
    //tr.addSelect("strings", null);
    //for (int ii=0; ii<numbStrings; ii++) {
    //  // Length of string starts at StringTable plus offset in StrIndTable
    //  String str = compXmlString(xml, sitOff, stOff, ii);
    //  tr.add(String.valueOf(ii), str);
    //}
    //tr.parent();

    // Step through the XML tree element tags and attributes
    int off = xmlTagOff;
    int indent = 0;
    int startTagLineNo = -2;
    while (off < cb) {
      int tag0 = LEW(xml, cb, off);
      //int tag1 = LEW(xml, off+1*4);
      int lineNo = LEW(xml, cb, off+2*4);
      //int tag3 = LEW(xml, off+3*4);
      int nameNsSi = LEW(xml, cb, off+4*4);
      int nameSi = LEW(xml, cb, off+5*4);

      if (tag0 == startTag) { // XML START TAG
        int tag6 = LEW(xml, cb, off+6*4);  // Expected to be 14001400
        int numbAttrs = LEW(xml, cb, off+7*4);  // Number of Attributes to follow
        //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
        off += 9*4;  // Skip over 6+3 words of startTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        //tr.addSelect(name, null);
        startTagLineNo = lineNo;

        // Look for the Attributes
        std::string sb;
        for (int ii=0; ii<numbAttrs; ii++) {
          int attrNameNsSi = LEW(xml, cb, off);  // AttrName Namespace Str Ind, or FFFFFFFF
          int attrNameSi = LEW(xml, cb, off+1*4);  // AttrName String Index
          int attrValueSi = LEW(xml, cb, off+2*4); // AttrValue Str Ind, or FFFFFFFF
          int attrFlags = LEW(xml, cb, off+3*4);  
          int attrResId = LEW(xml, cb, off+4*4);  // AttrValue ResourceId or dup AttrValue StrInd
          off += 5*4;  // Skip over the 5 words of an attribute

          std::string attrName = compXmlString(xml, cb, sitOff, stOff, attrNameSi);
          std::string attrValue = attrValueSi!=-1
            ? compXmlString(xml, cb, sitOff, stOff, attrValueSi)
            : "resourceID 0x"+toHexString(attrResId);
          sb.append(" "+attrName+"=\""+attrValue+"\"");
          //tr.add(attrName, attrValue);
        }
        prtIndent(indent, "<"+name+sb+">");
        indent++;

      } else if (tag0 == endTag) { // XML END TAG
        indent--;
        off += 6*4;  // Skip over 6 words of endTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        prtIndent(indent, "</"+name+">  (line "+toIntString(startTagLineNo)+"-"+toIntString(lineNo)+")");
        //tr.parent();  // Step back up the NobTree

      } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
        break;

      } else {
        prt("  Unrecognized tag code '"+toHexString(tag0)
          +"' at offset "+toIntString(off));
        break;
      }
    } // end of while loop scanning tags and attributes of XML tree
    prt("    end at offset "+off);
    } // end of decompressXML


    std::string compXmlString(const BYTE* xml, int cb, int sitOff, int stOff, int strInd) {
      if (strInd < 0) return std::string("");
      int strOff = stOff + LEW(xml, cb, sitOff+strInd*4);
      return compXmlStringAt(xml, cb, strOff);
    }

    void prt(std::string str)
    {
        printf("%s", str.c_str());
    }
    void prtIndent(int indent, std::string str) {
        char spaces[46];
        memset(spaces, ' ', sizeof(spaces));
        spaces[min(indent*2,  sizeof(spaces) - 1)] = 0;
        prt(spaces);
        prt(str);
        prt("\n");
    }


    // compXmlStringAt -- Return the string stored in StringTable format at
    // offset strOff.  This offset points to the 16 bit string length, which 
    // is followed by that number of 16 bit (Unicode) chars.
    std::string compXmlStringAt(const BYTE* arr, int cb, int strOff) {
        if (cb < strOff + 2) return std::string("");
      int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
      char* chars = new char[strLen + 1];
      chars[strLen] = 0;
      for (int ii=0; ii<strLen; ii++) {
          if (cb < strOff + 2 + ii * 2)
          {
              chars[ii] = 0;
              break;
          }
        chars[ii] = arr[strOff+2+ii*2];
      }
      std::string str(chars);
      free(chars);
      return str;
    } // end of compXmlStringAt


    // LEW -- Return value of a Little Endian 32 bit word from the byte array
    //   at offset off.
    int LEW(const BYTE* arr, int cb, int off) {
      return (cb > off + 3) ? ( arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
          | arr[off+1]<<8&0xff00 | arr[off]&0xFF ) : 0;
    } // end of LEW

    std::string toHexString(DWORD attrResId)
    {
        char ch[20];
        sprintf_s(ch, 20, "%lx", attrResId);
        return std::string(ch);
    }
    std::string toIntString(int i)
    {
        char ch[20];
        sprintf_s(ch, 20, "%ld", i);
        return std::string(ch);
    }
};

Cannot simply use PostgreSQL table name ("relation does not exist")

For me the problem was, that I had used a query to that particular table while Django was initialized. Of course it will then throw an error, because those tables did not exist. In my case, it was a get_or_create method within a admin.py file, that was executed whenever the software ran any kind of operation (in this case the migration). Hope that helps someone.

Display calendar to pick a date in java

I wrote a DateTextField component.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());
    }

    public DateTextField(String dateFormatPattern, Date date) {
        this(date);
        DEFAULT_DATE_FORMAT = dateFormatPattern;
    }

    public DateTextField(Date date) {
        setDate(date);
        setEditable(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        addListeners();
    }

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                }
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);
            }
        });
    }

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
                .getWindowAncestor(DateTextField.this);
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        }
        dateDialog.setLocation(getAppropriateLocation(owner, position));
        dateDialog.setVisible(true);
    }

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.setUndecorated(true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;
    }

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;
        }

        if (offsetY > 0) {
            result.y -= offsetY;
        }

        return result;
    }

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        }
        return dateFormat;
    }

    public void setText(Date date) {
        setDate(date);
    }

    public void setDate(Date date) {
        super.setText(getDefaultDateFormat().format(date));
    }

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();
        }
    }

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor = Color.orange;
        Color weekFontColor = Color.blue;
        Color dateFontColor = Color.black;
        Color weekendFontColor = Color.red;

        Color controlLineColor = Color.pink;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));
            setBackground(backGroundColor);

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);

            reflushWeekAndDay();
        }

        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.setBackground(controlLineColor);

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setName("Year");
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
            yearSpin.addChangeListener(this);
            panel.add(yearSpin);

            JLabel yearLabel = new JLabel("Year");
            yearLabel.setForeground(controlTextColor);
            panel.add(yearLabel);

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));
            monthSpin.setName("Month");
            monthSpin.addChangeListener(this);
            panel.add(monthSpin);

            JLabel monthLabel = new JLabel("Month");
            monthLabel.setForeground(controlTextColor);
            panel.add(monthLabel);

            return panel;
        }

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));
            panel.setBackground(Color.white);

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                cell.setHorizontalAlignment(JLabel.RIGHT);
                if (i == 0 || i == 6) {
                    cell.setForeground(weekendFontColor);
                } else {
                    cell.setForeground(weekFontColor);
                }
                panel.add(cell);
            }

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.setBorder(null);
                    numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
                    numBtn.setActionCommand(String
                            .valueOf(actionCommandId));
                    numBtn.setBackground(palletTableColor);
                    numBtn.setForeground(dateFontColor);
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                                return;
                            }
                            dayColorUpdate(true);
                            source.setForeground(todayBackColor);
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);
                            setDate(cal.getTime());

                            dateDialog.setVisible(false);
                        }
                    });

                    if (j == 0 || j == 6)
                        numBtn.setForeground(weekendFontColor);
                    else
                        numBtn.setForeground(dateFontColor);
                    daysButton[i][j] = numBtn;
                    panel.add(numBtn);
                    actionCommandId++;
                }

            return panel;
        }

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDate());
            return calendar;
        }

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();
        }

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();
        }

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
                daysButton[i][j].setForeground(dateFontColor);
            } else {
                daysButton[i][j].setForeground(todayBackColor);
            }
        }

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);
                    }
                    daysButton[i][j].setText(s);
                    dayNo++;
                }
            }
            dayColorUpdate(false);
        }

        public void stateChanged(ChangeEvent e) {
            dayColorUpdate(true);

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            setDate(cal.getTime());
            reflushWeekAndDay();
        }
    }
}

CSS div element - how to show horizontal scroll bars only?

you can also make it overflow: auto and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar

Phone Number Validation MVC

[DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.

According to the docs:

When you apply the DataTypeAttribute attribute to a data field you must do the following:

  • Issue validation errors as appropriate.

The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:

[Phone()]
public string PhoneNumber { get; set; }

However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.

Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

I had similar issue. I resolved it with just CSS.

Basically Object-fit: cover helps you achieve the task of maintaining the aspect ratio while positioning an image inside a div.

But the problem was Object-fit: cover was not working in IE and it was taking 100% width and 100% height and aspect ratio was distorted. In other words image zooming effect wasn't there which I was seeing in chrome.

The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.

Insert new column into table in sqlite?

You don't add columns between other columns in SQL, you just add them. Where they're put is totally up to the DBMS. The right place to ensure that columns come out in the correct order is when you select them.

In other words, if you want them in the order {name,colnew,qty,rate}, you use:

select name, colnew, qty, rate from ...

With SQLite, you need to use alter table, an example being:

alter table mytable add column colnew char(50)

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

LINQ to SQL Left Outer Join

I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.

Using LINQPad I created the following LINQ query:

//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}

Which was translated to the (slightly truncated) query below

 -- Region Parameters
 DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID],  [t1].[OrderID], [t1].[OnlineOrderID], (
    SELECT COUNT(*)
    FROM [OrderInfo] AS [t2]
    WHERE [t2].[CustomerID] = [t0].[CustomerID]
    ) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]

Notice the LEFT OUTER JOIN above.

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

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

It serves as padding.

A more complete answer is that a base64 encoded string doesn't always end with a =, it will only end with one or two = if they are required to pad the string out to the proper length.

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

How do I determine k when using k-means clustering?

You can choose the number of clusters by visually inspecting your data points, but you will soon realize that there is a lot of ambiguity in this process for all except the simplest data sets. This is not always bad, because you are doing unsupervised learning and there's some inherent subjectivity in the labeling process. Here, having previous experience with that particular problem or something similar will help you choose the right value.

If you want some hint about the number of clusters that you should use, you can apply the Elbow method:

First of all, compute the sum of squared error (SSE) for some values of k (for example 2, 4, 6, 8, etc.). The SSE is defined as the sum of the squared distance between each member of the cluster and its centroid. Mathematically:

SSE=?Ki=1?x?cidist(x,ci)2

If you plot k against the SSE, you will see that the error decreases as k gets larger; this is because when the number of clusters increases, they should be smaller, so distortion is also smaller. The idea of the elbow method is to choose the k at which the SSE decreases abruptly. This produces an "elbow effect" in the graph, as you can see in the following picture:

enter image description here

In this case, k=6 is the value that the Elbow method has selected. Take into account that the Elbow method is an heuristic and, as such, it may or may not work well in your particular case. Sometimes, there are more than one elbow, or no elbow at all. In those situations you usually end up calculating the best k by evaluating how well k-means performs in the context of the particular clustering problem you are trying to solve.

What is the Swift equivalent to Objective-C's "@synchronized"?

Why make it difficult and hassle with locks? Use Dispatch Barriers.

A dispatch barrier creates a synchronization point within a concurrent queue.

While it’s running, no other block on the queue is allowed to run, even if it’s concurrent and other cores are available.

If that sounds like an exclusive (write) lock, it is. Non-barrier blocks can be thought of as shared (read) locks.

As long as all access to the resource is performed through the queue, barriers provide very cheap synchronization.

Printing the last column of a line in a file

You don't see anything, because of buffering. The output is shown, when there are enough lines or end of file is reached. tail -f means wait for more input, but there are no more lines in file and so the pipe to grep is never closed.

If you omit -f from tail the output is shown immediately:

tail file | grep A1 | awk '{print $NF}'

@EdMorton is right of course. Awk can search for A1 as well, which shortens the command line to

tail file | awk '/A1/ {print $NF}'

or without tail, showing the last column of all lines containing A1

awk '/A1/ {print $NF}' file

Thanks to @MitchellTracy's comment, tail might miss the record containing A1 and thus you get no output at all. This may be solved by switching tail and awk, searching first through the file and only then show the last line:

awk '/A1/ {print $NF}' file | tail -n1

Initialize a string variable in Python: "" or None?

Either might be fine, but I don't think there is a definite answer.

  • If you want to indicate that the value has not been set, comparing with None is better than comparing with "", since "" might be a valid value,
  • If you just want a default value, "" is probably better, because its actually a string, and you can call string methods on it. If you went with None, these would lead to exceptions.
  • If you wish to indicate to future maintainers that a string is required here, "" can help with that.

Complete side note:

If you have a loop, say:

def myfunc (self, mystr = ""):
    for other in self.strs:
        mystr = self.otherfunc (mystr, other)

then a potential future optimizer would know that str is always a string. If you used None, then it might not be a string until the first iteration, which would require loop unrolling to get the same effects. While this isn't a hypothetical (it comes up a lot in my PHP compiler) you should certainly never write your code to take this into account. I just thought it might be interesting :)

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Add this line at the bottom of the gradle.

apply plugin: 'com.google.gms.google-services'

because it the top it does not work.I was facing similar problem.

TNS Protocol adapter error while starting Oracle SQL*Plus

You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.

Mapping a JDBC ResultSet to an object

using DbUtils...

The only problem I had with that lib was that sometimes you have relationships in your bean classes, DBUtils does not map that. It only maps the properties in the class of the bean, if you have other complex properties (refering other beans due to DB relationship) you'd have to create "indirect setters" as I call, which are setters that put values into those complex properties's properties.

Are PDO prepared statements sufficient to prevent SQL injection?

Personally I would always run some form of sanitation on the data first as you can never trust user input, however when using placeholders / parameter binding the inputted data is sent to the server separately to the sql statement and then binded together. The key here is that this binds the provided data to a specific type and a specific use and eliminates any opportunity to change the logic of the SQL statement.

angular js unknown provider

My case was dodgy typing

myApp.factory('Notify',funtion(){

function has a 'c' !

Scala Doubles, and Precision

I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:

  /** Constructs a `BigDecimal` using the decimal text representation of `Double` value `d`, rounding if necessary. */
  def decimal(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)

I'm going to stick to math manipulations as Kaito suggested.

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

Please look at this document

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

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

Goes into affect June 25, 2011.

Taken from the new FAQ:

What changes will result from randomization?

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

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

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

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Source

So as others mentioned, it's a convention.

How do you get the list of targets in a makefile?

This is a modification to jsp's very helpful answer (https://stackoverflow.com/a/45843594/814145). I like the idea of getting not only a list of targets but also their descriptions. jsp's Makefile puts the description as the comment, which I found often will be repeated in the target's description echo command. So instead, I extract the description from the echo command for each target.

Example Makefile:

.PHONY: all
all: build
        : "same as 'make build'"

.PHONY: build
build:
        @echo "Build the project"

.PHONY: clean
clean:
        @echo "Clean the project"

.PHONY: help
help:
        @echo -n "Common make targets"
        @echo ":"
        @cat Makefile | sed -n '/^\.PHONY: / h; /\(^\t@*echo\|^\t:\)/ {H; x; /PHONY/ s/.PHONY: \(.*\)\n.*"\(.*\)"/    make \1\t\2/p; d; x}'| sort -k2,2 |expand -t 20

Output of make help:

$ make help
Common make targets:
    make all        same as 'make build'
    make build      Build the project
    make clean      Clean the project
    make help       Common make targets

Notes:

  • Same as jsp's answer, only PHONY targets may be listed, which may or may not work for your case
  • In addition, it only lists those PHONY targets that have a echo or : command as the first command of the recipe. : means "do nothing". I use it here for those targets that no echo is needed, such as all target above.
  • There is an additional trick for the help target to add the ":" in the make help output.

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Safely override C++ virtual functions

As far as I know, can't you just make it abstract?

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.

How do I get logs from all pods of a Kubernetes replication controller?

One option is to set up cluster logging via Fluentd/ElasticSearch as described at https://kubernetes.io/docs/user-guide/logging/elasticsearch/. Once logs are in ES, it's easy to apply filters in Kibana to view logs from certain containers.

How to import jquery using ES6 syntax?

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

WPF: Grid with column/row margin/padding?

I ran into this problem while developing some software recently and it occured to me to ask WHY? Why have they done this...the answer was right there in front of me. A row of data is an object, so if we maintain object orientation, then the design for a particular row should be seperated (suppose you need to re-use the row display later on in the future). So I started using databound stack panels and custom controls for most data displays. Lists have made the occasional appearance but mostly the grid has been used only for primary page organization (Header, Menu Area, Content Area, Other Areas). Your custom objects can easily manage any spacing requirements for each row within the stack panel or grid (a single grid cell can contain the entire row object. This also has the added benefit of reacting properly to changes in orientation, expand/collapses, etc.

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
  </Grid.RowDefinitions>

  <custom:MyRowObject Style="YourStyleHereOrGeneralSetter" Grid.Row="0" />
  <custom:MyRowObject Style="YourStyleHere" Grid.Row="1" />
</Grid>

or

<StackPanel>
  <custom:MyRowObject Style="YourStyleHere" Grid.Row="0" />
  <custom:MyRowObject Style="YourStyleHere" Grid.Row="1" />
</StackPanel>

Your Custom controls will also inherit the DataContext if your using data binding...my personal favorite benefit of this approach.

Access parent's parent from javascript object

I have done something like this and it works like a charm.

Simple.

P.S. There is more the the object but I just posted the relevant part.

var exScript = (function (undefined) {
    function exScript() {
        this.logInfo = [];
        var that = this;
        this.logInfo.push = function(e) {
            that.logInfo[that.logInfo.length] = e;
            console.log(e);
        };
    }
})();

php - push array into array - key issue

I think you have to go for

$arrayname[indexname] = $value;

How to print out more than 20 items (documents) in MongoDB's shell?

You can use it inside of the shell to iterate over the next 20 results. Just type it if you see "has more" and you will see the next 20 items.

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

How to get values and keys from HashMap?

To get values and keys you could just use the methods values() and keySet() of HashMap

public static List getValues(Map map) {
    return new ArrayList(map.values());
}

public static List getKeys(Map map) {
    return new ArrayList(map.keySet());
}

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

You retrieve the system property that marks the bitness of this JVM with:

System.getProperty("sun.arch.data.model");

Possible results are:

  • "32" – 32-bit JVM
  • "64" – 64-bit JVM
  • "unknown" – Unknown JVM

As described in the HotSpot FAQ:

When writing Java code, how do I distinguish between 32 and 64-bit operation?

There's no public API that allows you to distinguish between 32 and 64-bit operation. Think of 64-bit as just another platform in the write once, run anywhere tradition. However, if you'd like to write code which is platform specific (shame on you), the system property sun.arch.data.model has the value "32", "64", or "unknown".

An example where this could be necessary is if your Java code depends on native libraries, and you need to determine whether to load the 32- or 64-bit version of the libraries on startup.

How do I check if a C++ string is an int?

The accepted answer will give a false positive if the input is a number plus text, because "stol" will convert the firsts digits and ignore the rest.

I like the following version the most, since it's a nice one-liner that doesn't need to define a function and you can just copy and paste wherever you need it.

#include <string>

...

std::string s;

bool has_only_digits = (s.find_first_not_of( "0123456789" ) == std::string::npos);

EDIT: if you like this implementation but you do want to use it as a function, then this should do:

bool has_only_digits(const string s){
  return s.find_first_not_of( "0123456789" ) == string::npos;
}

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I have the same issue , and I have resolved it using the steps mentioned above.but no when I have this issue again and i try the following,

RC(right click on web project) --> properties --> Deployment Assembly --> Add --> Java Build Path Entries --> Next -->

after clicking on next its only a blank window with the options Next and Fnish disabled.What can I do now?

How to import a JSON file in ECMAScript 6?

A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.

Configuration is as follows: React + Redux, Webpack 3.5.6

The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.

The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.

So here it is:

  fetch('../../package.json')
  .then(resp => resp.json())
  .then((packageJson) => {
    console.log(packageJson.version);
  });

Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.

Link to "pin it" on pinterest without generating a button

I had the same question. This works great in Wordpress!

<a href="//pinterest.com/pin/create/link/?url=<?php the_permalink();?>&amp;description=<?php the_title();?>">Pin this</a>

How can I change an element's class with JavaScript?

try

element.className='second'

_x000D_
_x000D_
function change(box) { box.className='second' }
_x000D_
.first  { width:  70px; height:  70px; background: #ff0                 }_x000D_
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
_x000D_
<div onclick="change(this)" class="first">Click me</div>
_x000D_
_x000D_
_x000D_

pip install gives error: Unable to find vcvarsall.bat

Simply because you don't have c++ compiler installed there in your machine, check the following

  • Download Microsoft Visual C++ 2008 from this page. That is a generally useful page anyway, so you should probably bookmark it. For Python 3.3+ use MS Visual C++ 2010. Install it.

  • Open Windows explorer (the file browser) and search for the location of ‘vcvarsall.bat’ and cut it to your clipboard.

  • run regedit from the Windows start key. You will need admin privilges.

  • Add a registry entry to HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (64 bit Windows) or HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (32 bit) as described here.

Hint: 0.9 in the registery directory is the currently installed version of your visual studio, if you running VS 2013, you have to find the path HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\12.0....

  • At the Windows start key, type cmd to get a command shell. If you need to, go to your virtual environment and run activate.bat.

  • pip install or whatever you use to install it.

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

'$on' itself returns function for unregister

 var unregister=  $rootScope.$on('$stateChangeStart',
            function(event, toState, toParams, fromState, fromParams, options) { 
                alert('state changing'); 
            });

you can call unregister() function to unregister that listener

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Can I append an array to 'formdata' in javascript?

var formData = new FormData; var arr = ['item1', 'item2', 'item3'];

arr.forEach(item => {
    formData.append(
        "myFile",item
    ); });

How to show an empty view with a RecyclerView?

Here is my class for show empty view, retry view (when load api failed) and loading progress for RecyclerView

public class RecyclerViewEmptyRetryGroup extends RelativeLayout {
    private RecyclerView mRecyclerView;
    private LinearLayout mEmptyView;
    private LinearLayout mRetryView;
    private ProgressBar mProgressBar;
    private OnRetryClick mOnRetryClick;

    public RecyclerViewEmptyRetryGroup(Context context) {
        this(context, null);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        if (child.getId() == R.id.recyclerView) {
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            return;
        }
        if (child.getId() == R.id.layout_empty) {
            mEmptyView = (LinearLayout) findViewById(R.id.layout_empty);
            return;
        }
        if (child.getId() == R.id.layout_retry) {
            mRetryView = (LinearLayout) findViewById(R.id.layout_retry);
            mRetryView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRetryView.setVisibility(View.GONE);
                    mOnRetryClick.onRetry();
                }
            });
            return;
        }
        if (child.getId() == R.id.progress_bar) {
            mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        }
    }

    public void loading() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    public void empty() {
        mEmptyView.setVisibility(View.VISIBLE);
        mRetryView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void retry() {
        mRetryView.setVisibility(View.VISIBLE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void success() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setOnRetryClick(OnRetryClick onRetryClick) {
        mOnRetryClick = onRetryClick;
    }

    public interface OnRetryClick {
        void onRetry();
    }
}

activity_xml

<...RecyclerViewEmptyRetryGroup
        android:id="@+id/recyclerViewEmptyRetryGroup">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"/>

        <LinearLayout
            android:id="@+id/layout_empty">
            ...
        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_retry">
            ...
        </LinearLayout>

        <ProgressBar
            android:id="@+id/progress_bar"/>

</...RecyclerViewEmptyRetryGroup>

enter image description here

The source is here https://github.com/PhanVanLinh/AndroidRecyclerViewWithLoadingEmptyAndRetry

How do I install Python packages on Windows?

As mentioned by Blauhirn after 2.7 pip is preinstalled. If it is not working for you it might need to be added to path.

However if you run Windows 10 you no longer have to open a terminal to install a module. The same goes for opening Python as well.

You can type directly into the search menu pip install mechanize, select command and it will install:

enter image description here

If anything goes wrong however it may close before you can read the error but still it's a useful shortcut.

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

df
   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))

IntelliJ how to zoom in / out

Double click Shift to open the quick actions. Then search for "Decrease Font Size" or "Increase Font Size" and hit Enter. To repeat the action you can doubleclick Shift and Enter

I prefer that way because it works even when you're using not your own Computer without opening settings. Also works without leaving fullscreen, which is useful if you are live coding.

Select elements by attribute in CSS

Is it possible to select elements in CSS by their HTML5 data attributes? This can easily be answered just by trying it, and the answer is, of course, yes. But this invariably leads us to the next question, 'Should we select elements in CSS by their HTML5 data attributes?' There are conflicting opinions on this.

In the 'no' camp is (or at least was, back in 2014) CSS legend Harry Roberts. In the article, Naming UI components in OOCSS, he wrote:

It’s important to note that although we can style HTML via its data-* attributes, we probably shouldn’t. data-* attributes are meant for holding data in markup, not for selecting on. This, from the HTML Living Standard (emphasis mine):

"Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements."

The W3C spec was frustratingly vague on this point, but based purely on what it did and didn't say, I think Harry's conclusion was perfectly reasonable.

Since then, plenty of articles have suggested that it's perfectly appropriate to use custom data attributes as styling hooks, including MDN's guide, Using data attributes. There's even a CSS methodology called CUBE CSS which has adopted the data attribute hook as the preferred way of adding styles to component 'exceptions' (known as modifiers in BEM).

Thankfully, the WHATWG HTML Living Standard has since added a few more words and even some examples (emphasis mine):

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

In this example, custom data attributes are used to store the result of a feature detection for PaymentRequest, which could be used in CSS to style a checkout page differently.

Authors should carefully design such extensions so that when the attributes are ignored and any associated CSS dropped, the page is still usable.


TL;DR: Yes, it's okay to use data-* attributes in CSS selectors, provided the page is still usable without them.

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I am developing an app to version 2.2, API version would in the 8th ... had the same error and the error told me it was to google maps API, all we did was change my ADV for my project API 2.2 and also for the API.

This worked for me and found the library API needed.

'Property does not exist on type 'never'

In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:

let response = {status: 200, data: []};

and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..

let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};

and assigning of the fake data:

response.data = fakeData;

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

Get text of the selected option with jQuery

Also u can consider this

$('#select_2').find('option:selected').text();

which might be a little faster solution though I am not sure.

How to add a Try/Catch to SQL Stored Procedure

Transact-SQL is a bit more tricky that C# or C++ try/catch blocks, because of the added complexity of transactions. A CATCH block has to check the xact_state() function and decide whether it can commit or has to rollback. I have covered the topic in my blog and I have an article that shows how to correctly handle transactions in with a try catch block, including possible nested transactions: Exception handling and nested transactions.

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
                 @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

AppFabric installation failed because installer MSI returned with error code : 1603

I was trying to re-install AppFabric 1.1 on my Dev Computer running Windows 8 and I get this error. I found here that adding this :

%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\  

to PSModulePath (System properties -> Environment Variables -> System variables) solved my issue.

Generating random number between 1 and 10 in Bash Shell Script

Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available

echo $(date +%S) | grep -o .$ | sed s/0/10/

Can vue-router open a link in a new tab?

Somewhere in your project, typically main.js or router.js

import Router from 'vue-router'

Router.prototype.open = function (routeObject) {
  const {href} = this.resolve(routeObject)
  window.open(href, '_blank')
}

In your component:

<div @click="$router.open({name: 'User', params: {ID: 123}})">Open in new tab</div>

PHP cURL HTTP CODE return 0

Try this:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

For loop example in MySQL

While loop syntax example in MySQL:

delimiter //

CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
  declare str VARCHAR(255) default '';
  declare x INT default 0;
  SET x = 1;

  WHILE x <= 5 DO
    SET str = CONCAT(str,x,',');
    SET x = x + 1;
  END WHILE;

  select str;
END//

Which prints:

mysql> call while_example();
+------------+
| str        |
+------------+
| 1,2,3,4,5, |
+------------+

REPEAT loop syntax example in MySQL:

delimiter //

CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
  DECLARE x INT;
  DECLARE str VARCHAR(255);
  SET x = 5;
  SET str = '';

  REPEAT
    SET str = CONCAT(str,x,',');
    SET x = x - 1;
    UNTIL x <= 0
  END REPEAT;

  SELECT str;
END//

Which prints:

mysql> call repeat_loop_example();
+------------+
| str        |
+------------+
| 5,4,3,2,1, |
+------------+

FOR loop syntax example in MySQL:

delimiter //

CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
  DECLARE x INT;
  DECLARE str VARCHAR(255);
  SET x = -5;
  SET str = '';

  loop_label: LOOP
    IF x > 0 THEN
      LEAVE loop_label;
    END IF;
    SET str = CONCAT(str,x,',');
    SET x = x + 1;
    ITERATE loop_label;
  END LOOP;

  SELECT str;

END//

Which prints:

mysql> call for_loop_example();
+-------------------+
| str               |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)

Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx

If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.

Visual Studio SignTool.exe Not Found

I have a windows 7 and installing the ClickOnce Tools was not enough.

The signtool.exe appeared after also installing the sdk:

selection in vs 2015

Java: getMinutes and getHours

From the Javadoc for Date.getHours

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)

So use

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);

and the equivalent for getMinutes.

How do I open a second window from the first window in WPF?

You can use this code:

private void OnClickNavigate(object sender, RoutedEventArgs e)
{
    NavigatedWindow navigatesWindow = new NavigatedWindow();
    navigatesWindow.ShowDialog();
}

Python - difference between two strings

What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj and zlib.decompressobj with the zdict parameter set to your "base word", e.g. afrykanerskojezyczny.

Caveats are zdict is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.

Modify SVG fill color when being served as Background-Image

This is my favorite method, but your browser support must be very progressive. With the mask property you create a mask that is applied to an element. Everywhere the mask is opaque, or solid, the underlying image shows through. Where it’s transparent, the underlying image is masked out, or hidden. The syntax for a CSS mask-image is similar to background-image.look at the codepenmask

Trying to embed newline in a variable in bash

var="a b c"
for i in $var
do
   p=`echo -e "$p"'\n'$i`
done
echo "$p"

The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

Removing duplicate rows in Notepad++

Whether the file is sorted or not, you can use below regex to remove duplicates in anywhere occurred in your file.

Find what: ^([^\r]*[^\n])(.*?)\r?\n\1$
Replace with: \1\2
Search Mode:

  • "Regular expression"
  • Check the ". matches newline" option

do "Replace All" as many time as possible until you see "0 occurrences were replaced"

How to get the Google Map based on Latitude on Longitude?

Firstly add a div with id.

<div id="my_map_add" style="width:100%;height:300px;"></div>

<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>

Can you have multiline HTML5 placeholder text in a <textarea>?

The html5 spec expressly rejects new lines in the place holder field. Versions of Webkit /will/ insert new lines when presented with line feeds in the placeholder, however this is incorrect behaviour and should not be relied upon.

I guess paragraphs aren't brief enough for w3 ;)

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

Defining a `required` field in Bootstrap

If wont work in case you have something like : novalidate="novalidate" attached to your form.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

How can I introduce multiple conditions in LIKE operator?

Here is an alternative way:

select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';

Here is the test code to verify:

create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col      |
+----------+
| ABCDEFG  |
| XYZ      |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)

Telnet is not recognized as internal or external command

You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well

How to connect to MongoDB in Windows?

I found that when I got this error it wasn't because I didn't have my default db path set up. It was because I was trying to run mongo.exe before running mongod.exe.

Error 500: Premature end of script headers

It is to do with file permissions and it happens on systems that have the suphp(usually cpanel/whost servers) installed.

Removing the write permission from anyone else but the owner(644|600) for the php files will fix the issue. That is how i got it fixed.

I hope this helps.

pycharm convert tabs to spaces automatically

Change the code style to use spaces instead of tabs:

spaces

Then select a folder you want to convert in the Project View and use Code | Reformat Code.

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

How to initialize a list of strings (List<string>) with many string values

List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");

Find largest and smallest number in an array

big=small=values[0]; //assigns element to be highest or lowest value

Should be AFTER fill loop

//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
    cout << "Enter value " << i << ": ";
    cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value

since when you declare array - it's unintialized (store some undefined values) and so, your big and small after assigning would store undefined values too.

And of course, you can use std::min_element, std::max_element, or std::minmax_element from C++11, instead of writing your loops.

Check if number is prime number

Shortest technique to find Prime Number using conventional way

    public string IsPrimeNumber(int Number)
    {
        int i = 2, j = Number / 2;
        for (; i <= j && Number % 2 != 0; i++);
        return (i - 1) == j ? "Prime Number" : "Not Prime Number";
    }

InputStream from a URL

Pure Java:

 urlToInputStream(url,httpHeaders);

With some success I use this method. It handles redirects and one can pass a variable number of HTTP headers asMap<String,String>. It also allows redirects from HTTP to HTTPS.

private InputStream urlToInputStream(URL url, Map<String, String> args) {
    HttpURLConnection con = null;
    InputStream inputStream = null;
    try {
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(15000);
        con.setReadTimeout(15000);
        if (args != null) {
            for (Entry<String, String> e : args.entrySet()) {
                con.setRequestProperty(e.getKey(), e.getValue());
            }
        }
        con.connect();
        int responseCode = con.getResponseCode();
        /* By default the connection will follow redirects. The following
         * block is only entered if the implementation of HttpURLConnection
         * does not perform the redirect. The exact behavior depends to 
         * the actual implementation (e.g. sun.net).
         * !!! Attention: This block allows the connection to 
         * switch protocols (e.g. HTTP to HTTPS), which is <b>not</b> 
         * default behavior. See: https://stackoverflow.com/questions/1884230 
         * for more info!!!
         */
        if (responseCode < 400 && responseCode > 299) {
            String redirectUrl = con.getHeaderField("Location");
            try {
                URL newUrl = new URL(redirectUrl);
                return urlToInputStream(newUrl, args);
            } catch (MalformedURLException e) {
                URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
                return urlToInputStream(newUrl, args);
            }
        }
        /*!!!!!*/

        inputStream = con.getInputStream();
        return inputStream;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Full example call

private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
        String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
        Map<String,String> httpHeaders=new Map<>();
        httpHeaders.put("Accept", "application/json");
        httpHeaders.put("User-Agent", "myApplication");
        httpHeaders.put("Authorization", "Basic " + encoded);
        return urlToInputStream(url,httpHeaders);
    }

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

C# Linq Where Date Between 2 Dates

I had a problem getting this to work.

I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.

this is my solution:

        var yesterday = DateTime.Today.AddDays(-1);
        var today = DateTime.Today;
        var tomorrow = DateTime.Today.AddDays(1);            
        var vm = new Model()
        {
            Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
            Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
            Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
        };

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Small correction, unescape and escape are deprecated, so:

function utf8_to_b64( str ) {
    return window.btoa(decodeURIComponent(encodeURIComponent(str)));
}

function b64_to_utf8( str ) {
     return decodeURIComponent(encodeURIComponent(window.atob(str)));
}


function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(encodeURIComponent(window.atob(str)));
}

How do you do block comments in YAML?

An alternative approach:

If

  • your YAML structure has well defined fields to be used by your app
  • AND you may freely add additional fields that won't mess up with your app

then

  • at any level you may add a new block text field named like "Description" or "Comment" or "Notes" or whatever

Example:

Instead of

# This comment
# is too long

use

Description: >
  This comment
  is too long

or

Comment: >
    This comment is also too long
    and newlines survive from parsing!

More advantages:

  1. If the comments become large and complex and have a repeating pattern, you may promote them from plain text blocks to objects
  2. Your app may -in the future- read or update those comments

How do I get a div to float to the bottom of its container?

Although this is very complicated but it is possible. I have check this code on latest Firefox and Google Chrome browser. Older browser may not support the css shape-outside property. For further detail check this reference.

_x000D_
_x000D_
window.addEventListener('load', function() {
  var imageHolder = document.querySelector('.image-holder');

  var containerHeight = document.querySelector('.container').offsetHeight;

  var imageHolderHeight = imageHolder.offsetHeight;

  var countPadding = containerHeight - imageHolderHeight;
  imageHolder.style.paddingTop = countPadding + 'px';
  containerHeight = document.querySelector('.container').offsetHeight;
  var x1 = '0' + 'px ' + countPadding + 'px';

  var x2 = imageHolder.offsetWidth + 'px' + ' ' + countPadding + 'px';

  var x3 = imageHolder.offsetWidth + 'px' + ' ' + containerHeight + 'px';

  var x4 = 0 + 'px' + ' ' + containerHeight + 'px';

  var value = 'polygon(' + x1 + ',' + x2 + ',' + x3 + ',' + x4 + ')';

  imageHolder.style.shapeOutside = value;

});
_x000D_
.container {
  width: 300px;
  text-align: justify;
  border: 1px solid black;
}

.image-holder {
  float: right;
}
_x000D_
<div class='container' style="">
  <div class='image-holder' style=''>
    <img class='bottom-right' style="width: 100px;" src="https://www.lwb.org.au/services/child-youth-and-family/static/b5cca79df7320248a77f6655a278190f/a6c62/img-index-banner.jpg" alt="">
  </div>
  <div>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Error quasi ut ipsam saepe, dignissimos, accusamus debitis ratione neque doloribus quis exercitationem iure! Harum quisquam ipsam velit distinctio tempora repudiandae eveniet.</div>

</div>
_x000D_
_x000D_
_x000D_

Is true == 1 and false == 0 in JavaScript?

Ah, the dreaded loose comparison operator strikes again. Never use it. Always use strict comparison, === or !== instead.

Bonus fact: 0 == ''

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

How to embed a PDF?

do you know about http://mozilla.github.io/pdf.js/ it is a project by mozila to render pdf inside of your html using canvas. it is super simple to use.

TypeError: p.easing[this.easing] is not a function

Jquery easing plugin renamed their effect function names from version 1.2 on. If you have some javascript depending on easing and it is not calling the right effect name it will throw this error.

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).

Is it possible to have multiple statements in a python lambda expression?

to demonstrate the lambda x:[f1(),f2()] effect which enables us to execute multiple functions in lambda. it also demonstrates the single line if else conditions if you really want to shrink the code.

  • note that f1() can be a lambda function also(recursive lambda or lambda within lambda). and that inner lambda can be a statement/function of your choice.
  • you can also put exec('statement') for example lambda x:[exec('a=[1]'),exec('b=2')]

a python implementation of touch(linux) command which creates empty files if they are not already existing.

def touch(fpath):
    check= os.path.exists(fpath)
    (lambda fname1:[open(fname1,"w+",errors="ignore").write(""),print('Touched',fname1)] 
    if not check else None) (fpath)

will print [ Touched fpath ] where fpath is file path given as input. will do nothing if file already exist.

the (lambda x: [ f(x), f2(x) ] ) (inp) <- we pass the 'inp' as input to lambda which in this case is the fpath.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915) and make sure you add other jar files present in lib and ooxml-lib folders.

Hope this helps!!!:)

'pip' is not recognized as an internal or external command

For me the command:

set PATH=%PATH%;C:\Python34\Scripts

worked immediately (try after echo %PATH% and you will see that your path has the value C:\Python34\Scripts).

Thanks to: Adding a directory to the PATH environment variable in Windows

Enum String Name from Value

SOLUTION:

int enumValue = 2; // The value for which you want to get string 
string enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);

Also, using GetName is better than Explicit casting of Enum.

[Code for Performance Benchmark]

Stopwatch sw = new Stopwatch (); sw.Start (); sw.Stop (); sw.Reset ();
double sum = 0;
int n = 1000;
Console.WriteLine ("\nGetName method way:");
for (int i = 0; i < n; i++) {
   sw.Start ();
   string t = Enum.GetName (typeof (Roles), roleValue);
   sw.Stop ();
   sum += sw.Elapsed.TotalMilliseconds;
   sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Getname method casting way: {sum / n}");
Console.WriteLine ("\nExplicit casting way:");
for (int i = 0; i < n; i++) {
   sw.Start ();
   string t = ((Roles)roleValue).ToString ();
   sw.Stop ();
   sum += sw.Elapsed.TotalMilliseconds;
   sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Explicit casting way: {sum / n}");

[Sample result]

GetName method way:
Average of 1000 runs using Getname method casting way: 0.000186899999999998
Explicit casting way:
Average of 1000 runs using Explicit casting way: 0.000627900000000002

getActivity() returns null in Fragment function

Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)

Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).

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

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

PowerShell script to return versions of .NET Framework on a machine?

Added v4.8 support to the script:

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
  name="Product"
  expression={
      switch -regex ($_.Release) {
        "378389" { [Version]"4.5" }
        "378675|378758" { [Version]"4.5.1" }
        "379893" { [Version]"4.5.2" }
        "393295|393297" { [Version]"4.6" }
        "394254|394271" { [Version]"4.6.1" }
        "394802|394806" { [Version]"4.6.2" }
        "460798|460805" { [Version]"4.7" }
        "461308|461310" { [Version]"4.7.1" }
        "461808|461814" { [Version]"4.7.2" }
        "528040|528049" { [Version]"4.8" }
        {$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
      }
    }
}

C Macro definition to determine big endian or little endian machine?

Macro to find endiannes

#define ENDIANNES() ((1 && 1 == 0) ? printf("Big-Endian"):printf("Little-Endian"))

or

#include <stdio.h>

#define ENDIAN() { \
volatile unsigned long ul = 1;\
volatile unsigned char *p;\
p = (volatile unsigned char *)&ul;\
if (*p == 1)\
puts("Little endian.");\
else if (*(p+(sizeof(unsigned long)-1)) == 1)\
puts("Big endian.");\
else puts("Unknown endian.");\
}

int main(void) 
{
       ENDIAN();
       return 0;
}

How to find the length of an array in shell?

$ a=(1 2 3 4)
$ echo ${#a[@]}
4

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

How to import and export components using React + ES6 + webpack?

Try defaulting the exports in your components:

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class MyNavbar extends React.Component {
    render(){
      return (
        <Navbar className="navbar-dark" fluid>
        ...
        </Navbar>
      );
    }
}

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

Get Element value with minidom with Python

Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)

images = xml.getElementsByTagName("imageUrl")
for i in images:
    print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

In ONLINE mode the new index is built while the old index is accessible to reads and writes. any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied). See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.

In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table. No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.

Note that in SQL Server 2012 the restriction on LOBs was lifted, see Online Index Operations for indexes containing LOB columns.

How do I find the caller of a method using stacktrace or reflection?

An alternative solution can be found in a comment to this request for enhancement. It uses the getClassContext() method of a custom SecurityManager and seems to be faster than the stack trace method.

The following program tests the speed of the different suggested methods (the most interesting bit is in the inner class SecurityManagerMethod):

/**
 * Test the speed of various methods for getting the caller class name
 */
public class TestGetCallerClassName {

  /**
   * Abstract class for testing different methods of getting the caller class name
   */
  private static abstract class GetCallerClassNameMethod {
      public abstract String getCallerClassName(int callStackDepth);
      public abstract String getMethodName();
  }

  /**
   * Uses the internal Reflection class
   */
  private static class ReflectionMethod extends GetCallerClassNameMethod {
      public String getCallerClassName(int callStackDepth) {
          return sun.reflect.Reflection.getCallerClass(callStackDepth).getName();
      }

      public String getMethodName() {
          return "Reflection";
      }
  }

  /**
   * Get a stack trace from the current thread
   */
  private static class ThreadStackTraceMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return Thread.currentThread().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Current Thread StackTrace";
      }
  }

  /**
   * Get a stack trace from a new Throwable
   */
  private static class ThrowableStackTraceMethod extends GetCallerClassNameMethod {

      public String getCallerClassName(int callStackDepth) {
          return new Throwable().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Throwable StackTrace";
      }
  }

  /**
   * Use the SecurityManager.getClassContext()
   */
  private static class SecurityManagerMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return mySecurityManager.getCallerClassName(callStackDepth);
      }

      public String getMethodName() {
          return "SecurityManager";
      }

      /** 
       * A custom security manager that exposes the getClassContext() information
       */
      static class MySecurityManager extends SecurityManager {
          public String getCallerClassName(int callStackDepth) {
              return getClassContext()[callStackDepth].getName();
          }
      }

      private final static MySecurityManager mySecurityManager =
          new MySecurityManager();
  }

  /**
   * Test all four methods
   */
  public static void main(String[] args) {
      testMethod(new ReflectionMethod());
      testMethod(new ThreadStackTraceMethod());
      testMethod(new ThrowableStackTraceMethod());
      testMethod(new SecurityManagerMethod());
  }

  private static void testMethod(GetCallerClassNameMethod method) {
      long startTime = System.nanoTime();
      String className = null;
      for (int i = 0; i < 1000000; i++) {
          className = method.getCallerClassName(2);
      }
      printElapsedTime(method.getMethodName(), startTime);
  }

  private static void printElapsedTime(String title, long startTime) {
      System.out.println(title + ": " + ((double)(System.nanoTime() - startTime))/1000000 + " ms.");
  }
}

An example of the output from my 2.4 GHz Intel Core 2 Duo MacBook running Java 1.6.0_17:

Reflection: 10.195 ms.
Current Thread StackTrace: 5886.964 ms.
Throwable StackTrace: 4700.073 ms.
SecurityManager: 1046.804 ms.

The internal Reflection method is much faster than the others. Getting a stack trace from a newly created Throwable is faster than getting it from the current Thread. And among the non-internal ways of finding the caller class the custom SecurityManager seems to be the fastest.

Update

As lyomi points out in this comment the sun.reflect.Reflection.getCallerClass() method has been disabled by default in Java 7 update 40 and removed completely in Java 8. Read more about this in this issue in the Java bug database.

Update 2

As zammbi has found, Oracle was forced to back out of the change that removed the sun.reflect.Reflection.getCallerClass(). It is still available in Java 8 (but it is deprecated).

Update 3

3 years after: Update on timing with current JVM.

> java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
> java TestGetCallerClassName
Reflection: 0.194s.
Current Thread StackTrace: 3.887s.
Throwable StackTrace: 3.173s.
SecurityManager: 0.565s.

JSON datetime between Python and JavaScript

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

I.e. this works:

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}

And this too:

>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]

But this doesn't work as expected:

>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']

Here's the code:

__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

Possible reasons for timeout when trying to access EC2 instance

To enable ssh access from the Internet for instances in a VPC subnet do the following:

  • Attach an Internet gateway to your VPC.
  • Ensure that your subnet's route table points to the Internet gateway.
  • Ensure that instances in your subnet have a globally unique IP address (public IPv4 address, Elastic IP address, or IPv6 address).
  • Ensure that your network access control (at VPC Level) and security group rules (at ec2 level) allow the relevant traffic to flow to and from your instance. Ensure your network Public IP address is enabled for both. By default, Network AcL allow all inbound and outbound traffic except explicitly configured otherwise

Run an Ansible task only when the variable contains a specific string

In Ansible version 2.9.2:

If your variable variable1 is declared:

when: "'value' in variable1"

If you registered variable1 then:

when: "'value' in variable1.stdout"

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.

This is normally more an issue with ToMany than ToOnes. For example,

Select e from Employee e 
join fetch e.phones p 
where p.areaCode = '613'

This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.

Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

How to set cornerRadius for only top-left and top-right corner of a UIView?

A lovely extension to reuse Yunus Nedim Mehel solution

Swift 2.3

extension UIView {
func roundCornersWithLayerMask(cornerRadii: CGFloat, corners: UIRectCorner) {
    let path = UIBezierPath(roundedRect: bounds,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: cornerRadii, height: cornerRadii))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    layer.mask = maskLayer
} }

Usage

let view = UIView()
view.roundCornersWithLayerMask(10,[.TopLeft,.TopRight])

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.

Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.

Laravel 4: Redirect to a given url

This worked for me in Laravel 5.8

return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');

Or instead of / you can use

use Redirect;

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to enter quotes in a Java string?

This tiny java method will help you produce standard CSV text of a specific column.

public static String getStandardizedCsv(String columnText){

    //contains line feed ?
    boolean containsLineFeed = false;
    if(columnText.contains("\n")){
        containsLineFeed = true;
    }

    boolean containsCommas = false;
    if(columnText.contains(",")){
        containsCommas = true;
    }

    boolean containsDoubleQuotes = false;
    if(columnText.contains("\"")){
        containsDoubleQuotes = true;
    }

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

    if(containsLineFeed || containsCommas || containsDoubleQuotes){
        columnText = "\"" + columnText + "\"";
    }

    return columnText;
}

Cannot import XSSF in Apache POI

After trying multiple things,what really worked was: 1. downloading "poi" and "poi-ooxml" manually 2.Adding these d/w jars into "Maven Dependencies"

Align an element to bottom with flexbox

You can use auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

So you can use one of these (or both):

p { margin-bottom: auto; } /* Push following elements to the bottom */
a { margin-top: auto; } /* Push it and following elements to the bottom */

_x000D_
_x000D_
.content {_x000D_
  height: 200px;_x000D_
  border: 1px solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
  margin: 0;_x000D_
}_x000D_
a {_x000D_
  margin-top: auto;_x000D_
}
_x000D_
<div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some text more or less</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternatively, you can make the element before the a grow to fill the available space:

p { flex-grow: 1; } /* Grow to fill available space */

_x000D_
_x000D_
.content {_x000D_
  height: 200px;_x000D_
  border: 1px solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
  margin: 0;_x000D_
}_x000D_
p {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some text more or less</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.

Create an ArrayList of unique values

Just Override the boolean equals() method of custom object. Say you have an ArrayList with custom field f1, f2, ... override

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof CustomObject)) return false;

    CustomObject object = (CustomObject) o;

    if (!f1.equals(object.dob)) return false;
    if (!f2.equals(object.fullName)) return false;
    ...
    return true;
}

and check using ArrayList instance's contains() method. That's it.

Concat all strings inside a List<string> using LINQ

I think that if you define the logic in an extension method the code will be much more readable:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

App crashing when trying to use RecyclerView on android 5.0

If I where you I will do this. onView(withId(android.R.id.list)).perform(RecyclerViewActions.scrollToPosition(3)); android.R.id.list change it to your list id and position will be your position inside your array.

How do I remove lines between ListViews on Android?

I find it easier to implement it in the XML file as it can be harder to trace the line of code in a class with hundreds of lines. For the XML you can use "null":

android:divider="@null"

How do I sort arrays using vbscript?

You either have to write your own sort by hand, or maybe try this technique:

http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83

You can freely intermix server side javascript with VBScript, so wherever VBScript falls short, switch to javascript.

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

jQuery, get html of a whole element

You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just

var child = $('#div div:nth-child(1)').clone();  

var child2 = $('#div div:nth-child(2)').clone();

You will get this for first query as asked in question

<div id="div1">
     <p>Some Content</p>
</div>

php hide ALL errors

Use PHP error handling functions to handle errors. How you do it depends on your needs. This system will intercept all errors and forward it however you want it Or supress it if you ask it to do so

http://php.net/manual/en/book.errorfunc.php

How to write lists inside a markdown table?

Yes, you can merge them using HTML. When I create tables in .md files from Github, I always like to use HTML code instead of markdown.

Github Flavored Markdown supports basic HTML in .md file. So this would be the answer:

Markdown mixed with HTML:

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|

Or pure HTML:

<table>
  <tbody>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
    <tr>
      <td>
        <ul>
          <li>item1</li>
          <li>item2</li>
        </ul>
      </td>
      <td align="center">See the list</td>
      <td align="right">from the first column</td>
    </tr>
  </tbody>
</table>

This is how it looks on Github:

How to do sed like text replace with python?

I wanted to be able to find and replace text but also include matched groups in the content I insert. I wrote this short script to do that:

https://gist.github.com/turtlemonvh/0743a1c63d1d27df3f17

The key component of that is something that looks like like this:

print(re.sub(pattern, template, text).rstrip("\n"))

Here's an example of how that works:

# Find everything that looks like 'dog' or 'cat' followed by a space and a number
pattern = "((cat|dog) (\d+))"

# Replace with 'turtle' and the number. '3' because the number is the 3rd matched group.
# The double '\' is needed because you need to escape '\' when running this in a python shell
template = "turtle \\3"

# The text to operate on
text = "cat 976 is my favorite"

Calling the above function with this yields:

turtle 976 is my favorite

PHP Get Site URL Protocol - http vs https

I've tested the most voted answer and it didn't work for me, I ended up using:

$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';

How to set the DefaultRoute to another Route in React Router

The preferred method is to use the react router IndexRoutes component

You use it like this (taken from the react router docs linked above):

<Route path="/" component={App}>
    <IndexRedirect to="/welcome" />
    <Route path="welcome" component={Welcome} />
    <Route path="about" component={About} />
</Route>

How to download Visual Studio 2017 Community Edition for offline installation?

Here you can download visual studio 2017 initial installer:

https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio?view=vs-2017

Run it and after few minutes it will ask what components do you want to install and in the right bottom there will be two option
"Install while downloading"
"Download all, then install"

Select any option and click install.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

I found mine here on a OSX system /usr/local/var/mongodb

What's the difference between 'git merge' and 'git rebase'?

I really love this excerpt from 10 Things I hate about git (it gives a short explanation for rebase in its second example):

3. Crappy documentation

The man pages are one almighty “f*** you”1. They describe the commands from the perspective of a computer scientist, not a user. Case in point:

git-push – Update remote refs along with associated objects

Here’s a description for humans:

git-push – Upload changes from your local repository into a remote repository

Update, another example: (thanks cgd)

git-rebase – Forward-port local commits to the updated upstream head

Translation:

git-rebase – Sequentially regenerate a series of commits so they can be 
             applied directly to the head node

And then we have

git-merge - Join two or more development histories together

which is a good description.


1. uncensored in the original

How do I display images from Google Drive on a website?

Update 18/02/2017 Google had depreciated free hosting feature on Google drive and now you cannot host your static website on Google drive for free.

But if you want to host your JavaScript and CSS and Images file on Google drive then you can still do so. You just need to obtain the permalink of the file. following updated tutorial (2017).

http://www.bloggerseolab.com/2017/02/host-images-javascript-and-css-on-google-drive.html

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Differences between JDK and Java SDK

Yes, there is a difference between the SDK and the JDK. Most of people forget that Java Platform is not only used to develop programs in Java language. The JVM supports some other languages also. Thus, making it clear, the SDK is the generic bundle of software that supports software creation in a variety of languages like Clojure, Groovy, Scala, JRuby, and others. The JDK is the specific bundle to develop software in Java language, containing all Java standard API to do so. (I hope I've explaned it well, since I actually do not speak english)

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I have the same question.

You should add some dependencies in build.gradle, just looks like this

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':libcocos2dx')
    compile 'com.google.firebase:firebase-ads:11.6.0'
// the key point line
    compile 'com.google.android.gms:play-services-auth:11.6.0'
}

Render partial from different folder (not shared)

Create a Custom View Engine and have a method that returns a ViewEngineResult In this example you just overwrite the _options.ViewLocationFormats and add your folder directory :

public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
        {
            var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);
            var areaName = context.GetNormalizedRouteValue(AREA_KEY);

            var checkedLocations = new List<string>();
            foreach (var location in _options.ViewLocationFormats)
            {
                var view = string.Format(location, viewName, controllerName);
                if (File.Exists(view))
                {
                    return ViewEngineResult.Found("Default", new View(view, _ViewRendering));
                }
                checkedLocations.Add(view);
            }

            return ViewEngineResult.NotFound(viewName, checkedLocations);
        }

Example: https://github.com/AspNetMonsters/pugzor

Populating a data frame in R in a loop

It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:

  1. Preallocate your data.frame. This is not recommended because indexing is slow for data.frames.
  2. Use another data structure in the loop and transform into a data.frame afterwards. A list is very useful here.

Example to illustrate the general approach:

mylist <- list() #create an empty list

for (i in 1:5) {
  vec <- numeric(5) #preallocate a numeric vector
  for (j in 1:5) { #fill the vector
    vec[j] <- i^j 
  }
  mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix

In this example it is not necessary to use a list, you could preallocate a matrix. However, if you do not know how many iterations your loop will need, you should use a list.

Finally here is a vectorized alternative to the example loop:

outer(1:5,1:5,function(i,j) i^j)

As you see it's simpler and also more efficient.

Google Colab: how to read data from my google drive?

You can't permanently store a file on colab. Though you can import files from your drive and everytime when you are done with file you can save it back.

To mount the google drive to your Colab session

from google.colab import drive
drive.mount('/content/gdrive')

you can simply write to google drive as you would to a local file system Now if you see your google drive will be loaded in the Files tab. Now you can access any file from your colab, you can write as well as read from it. The changes will be done real time on your drive and anyone having the access link to your file can view the changes made by you from your colab.

Example

with open('/content/gdrive/My Drive/filename.txt', 'w') as f:
   f.write('values')

CSV API for Java

There is also CSV/Excel Utility. It assumes all thos data is table-like and delivers data from Iterators.

How do I add PHP code/file to HTML(.html) files?

I think writing PHP into an .html file is confusing and anti-natural. Why would you do that??

Anyway, if what you want is to execute PHP files and show them as .html in the address bar, an easiest solution would be using .php as normal, and write a rule in your .htaccess like this:

RewriteRule ^([^.]+)\.html$ $1.php [L]

ssh : Permission denied (publickey,gssapi-with-mic)

please make sure following changes should be uncommented, which I did and got succeed in centos7

vi /etc/ssh/sshd_config

1.PubkeyAuthentication yes

2.PasswordAuthentication yes

3.GSSAPIKeyExchange no

4.GSSAPICleanupCredentials no

systemctl restart sshd

ssh-keygen

chmod 777 /root/.ssh/id_rsa.pub 

ssh-copy-id -i /root/.ssh/id_rsa.pub user@ipaddress

thank you all and good luck

Arrow operator (->) usage in C

#include<stdio.h>
struct examp{
int number;
};
struct examp a,*b=&a;`enter code here`
main()
{
a.number=5;
/* a.number,b->number,(*b).number produces same output. b->number is mostly used in linked list*/
   printf("%d \n %d \n %d",a.number,b->number,(*b).number);
}

output is 5 5 5

How to escape double quotes in a title attribute

Perhaps you can use JavaScript to solve your cross-browser problem. It uses a different escape mechanism, one with which you're obviously already familiar:

(reference-to-the-tag).title = "Some \"text\"";

It doesn't strictly separate the functions of HTML, JavaScript, and CSS the way folks want you to nowadays, but whom do you need to make happy? Your users or techies you don't know?

What's the difference between IFrame and Frame?

Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.

How can I set the background color of <option> in a <select> element?

I had this problem too. I found setting the appearance to none helped.

.class {
    appearance:none;
    -moz-appearance:none;
    -webkit-appearance:none;

    background-color: red;
}

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Is there an equivalent of CSS max-width that works in HTML emails?

The short answer: no.

The long answer:

Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.

It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

Creating an array from a text file in Bash

You can simply read each line from the file and assign it to an array.

#!/bin/bash
i=0
while read line 
do
        arr[$i]="$line"
        i=$((i+1))
done < file.txt

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Right click your project select manage Nuget packages, type newtonsoft in the search box and install the latest version. Then Run your App

The import javax.servlet can't be resolved

You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar in Tomcat's lib folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.

If you want to leave the JAR in Tomcat's lib folder:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click the Libraries tab
  • Click Add External JARs...
  • Browse to find servlet-api.jar and select it.
  • Click OK to update the build path.

Or, if you copy the JAR into your project:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click Add JARs...
  • Find servlet-api.jar in your project and select it.
  • Click OK to update the build path.

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

How to write file in UTF-8 format?

file_get_contents / file_put_contents will not magically convert encoding.

You have to convert the string explicitly; for example with iconv() or mb_convert_encoding().

Try this:

$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);

Or alternatively, with PHP's stream filters:

$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));

How to Toggle a div's visibility by using a button click

You can easily do it with jquery toggle. By this toggle or slideToggle you will get nice animation and effect also.

_x000D_
_x000D_
$(function(){_x000D_
  $("#details_content").css("display","none");_x000D_
  $(".myButton").click(function(){_x000D_
    $("#details_content").slideToggle(1000);_x000D_
  })  _x000D_
})
_x000D_
<div class="main">_x000D_
    <h2 class="myButton" style="cursor:pointer">Click Me</h2>_x000D_
    <div id="details_content">_x000D_
        <h1> Lorem Ipsum is simply dummy text</h1> _x000D_
        <p>    of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How can I determine the current CPU utilization from the shell?

The command uptime gives you load averages for the past 1, 5, and 15 minutes.

One line if in VB .NET

Or

IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

We wanted to pass a different config file for different environments -- one for production, dev and testing. This is the code in the gulp file:

_x000D_
_x000D_
//passing in flag to gulp to set environment_x000D_
//var env = gutil.env.env;_x000D_
_x000D_
if (typeof gutil.env.env === 'string') {_x000D_
  process.env.NODE_ENV = gutil.env.env;_x000D_
}
_x000D_
_x000D_
_x000D_

This is the code in the app.js file:

_x000D_
_x000D_
  if(env === 'testing'){_x000D_
      var Config = require('./config.testing.js');_x000D_
      var Api = require('./api/testing.js')(Config.web);_x000D_
    }_x000D_
    else if(env === 'dev'){_x000D_
       Config = require('./config.dev.js');_x000D_
        Api = require('./api/dev.js').Api;_x000D_
    }_x000D_
    else{_x000D_
       Config = require('./config.production.js');_x000D_
       Api = require('./api/production.js')(Config.web);_x000D_
    }
_x000D_
_x000D_
_x000D_

And then to run it gulp --env=testing

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

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

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

JavaScript closure inside loops – simple practical example

Already many valid answers to this question. Not many using a functional approach though. Here is an alternative solution using the forEach method, which works well with callbacks and closures:

let arr = [1,2,3];

let myFunc = (val, index) => { console.log('val: '+val+'\nindex: '+index); };

arr.forEach(myFunc);

ng-repeat :filter by single field

You can filter by an object with a property matching the objects you have to filter on it:

app.controller('FooCtrl', function($scope) {
   $scope.products = [
       { id: 1, name: 'test', color: 'red' },
       { id: 2, name: 'bob', color: 'blue' }
       /*... etc... */
   ];
});
<div ng-repeat="product in products | filter: { color: 'red' }"> 

This can of course be passed in by variable, as Mark Rajcok suggested.

What does the "map" method do in Ruby?

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.

Where is this helpful, and what is the difference between map! and each? Here is an example:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

The output:

Danil is a programmer
Edmund is a programmer

WSDL validator?

If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.

Print newline in PHP in single quotes

No, according to documentation, PHP recognize no special symbol in single quotes. And there is no single reason to use single quotes as much as possible

How do I remove blank pages coming between two chapters in Appendix?

You can also use \openany, \openright and \openleft commands:

\documentclass{memoir}
\begin{document}

\openany
\appendix

\openright
\appendixpage
This is the appendix.

\end{document}

Difference between static class and singleton pattern?

  1. We can create the object of singleton class and pass it to method.

  2. Singleton class doesn't any restriction of inheritance.

  3. We can't dispose the objects of a static class but can singleton class.

How to hide code from cells in ipython notebook visualized with nbviewer?

There is a nice solution provided here that works well for notebooks exported to HTML. The website even links back here to this SO post, but I don't see Chris's solution here! (Chris, where are you at?)

This is basically the same solution as the accepted answer from harshil, but it has the advantage of hiding the toggle code itself in the exported HTML. I also like that this approach avoids the need for the IPython HTML function.

To implement this solution, add the following code to a 'Raw NBConvert' cell at the top of your notebook:

<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()">
  <input type="submit" id="toggleButton" value="Show Code">
</form>

Then simply export the notebook to HTML. There will be a toggle button at the top of the notebook to show or hide the code.

Chris also provides an example here.

I can verify that this works in Jupyter 5.0.0

Update: It is also convenient to show/hide the div.prompt elements along with the div.input elements. This removes the In [##]: and Out: [##] text and reduces the margins on the left.