Programs & Examples On #Streaminsight

StreamInsight is a Complex Event Processing (CEP) product by Microsoft. It is meant to be run self-managed servers, in contrast to "Austin" which is the Azure-hosted version of the same product.

Keep the order of the JSON keys during JSON conversion to CSV

I know this is solved and the question was asked long time ago, but as I'm dealing with a similar problem, I would like to give a totally different approach to this:

For arrays it says "An array is an ordered collection of values." at http://www.json.org/ - but objects ("An object is an unordered set of name/value pairs.") aren't ordered.

I wonder why that object is in an array - that implies an order that's not there.

{
"items":
[
    {
        "WR":"qwe",
        "QU":"asd",
        "QA":"end",
        "WO":"hasd",
        "NO":"qwer"
    },
]
}

So a solution would be to put the keys in a "real" array and add the data as objects to each key like this:

{
"items":
[
    {"WR": {"data": "qwe"}},
    {"QU": {"data": "asd"}},
    {"QA": {"data": "end"}},
    {"WO": {"data": "hasd"}},
    {"NO": {"data": "qwer"}}
]
}

So this is an approach that tries to rethink the original modelling and its intent. But I haven't tested (and I wonder) if all involved tools would preserve the order of that original JSON array.

UIAlertView first deprecated IOS 9

 UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Are you sure you want to logout?"
                                 message:@""
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"Logout"
                                style:UIAlertActionStyleDestructive
                                handler:^(UIAlertAction * action)
                                {

                                }];

    UIAlertAction* noButton = [UIAlertAction
                               actionWithTitle:@"Cancel"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button
                               }];

    [alert addAction:noButton];
    [alert addAction:yesButton];

    [self presentViewController:alert animated:YES completion:nil];

How do I determine if a port is open on a Windows server?

On Windows you can use

netstat -na | find "your_port"

to narrow down the results. You can also filter for LISTENING, ESTABLISHED, TCP and such. Mind it's case-sensitive though.

Fastest way to convert Image to Byte array

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful

Use jQuery to change a second select list based on the first select list option

Try to use it:

Drop-down box dependent on the option selected in another drop-down box. Use jQuery to change a second select list based on the first select list option.

<asp:HiddenField ID="hdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:TextBox ID="txtOfferId" CssClass="hidden" ClientIDMode="Static" runat="server" Text="0" />
<asp:HiddenField ID="SelectedhdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:HiddenField ID="SelectedhdfOfferId" ClientIDMode="Static" runat="server" Value="0" />

<div class="col-lg-2 col-md-2 col-sm-12">
    <span>Service</span>
    <asp:DropDownList ID="ddlService" ClientIDMode="Static" runat="server" CssClass="form-control">
    </asp:DropDownList>
</div>
<div class="col-lg-2 col-md-2 col-sm-12">
    <span>Offer</span>
    <asp:DropDownList ID="ddlOffer" ClientIDMode="Static" runat="server" CssClass="form-control">
    </asp:DropDownList>
</div>

Use jQuery library in your web page.

<script type="text/javascript">
    $(document).ready(function () {
        ucBindOfferByService();
        $("#ddlOffer").val($('#txtOfferId').val());
    });

    $('#ddlOffer').on('change', function () {
        $("#txtOfferId").val($('#ddlOffer').val());
    });

    $('#ddlService').on('change', function () {
        $("#SelectedhdfOfferId").val("0");
        SetServiceIds();
        var SelectedServiceId = $('#ddlService').val();
        $("#SelectedhdfServiceId").val(SelectedServiceId);
        if (SelectedServiceId == '0') {
        }
        ucBindOfferByService();
        SetOfferIds();
    });

    function ucBindOfferByService() {
        GetVendorOffer();
        var SelectedServiceId = $('#ddlService').val();
        if (SelectedServiceId == '0') {
            $("#ddlOffer").empty();
            $("#ddlOffer").append($("<option></option>").val("0").html("All"));
        }
        else {
            $("#ddlOffer").empty();
            $(document.ucVendorServiceList).each(function () {
                if ($("#ddlOffer").html().length == "0") {
                    $("#ddlOffer").append($("<option></option>").val("0").html("All"));
                }
                $("#ddlOffer").append($("<option></option>").val(this.OfferId).html(this.OfferName));
            });
        }
    }

    function GetVendorOffer() {
        var param = JSON.stringify({ UserId: $('#hdfUserId').val(), ServiceId: $('#ddlService').val() });
        AjaxCall("DemoPage.aspx", "GetOfferList", param, OnGetOfferList, AjaxCallError);
    }

    function OnGetOfferList(response) {
        if (response.d.length > 0)
            document.ucVendorServiceList = JSON.parse(response.d);
    }

    function SetServiceIds() {
        var SelectedServiceId = $('#ddlService').val();
        var ServiceIdCSV = ',';
        if (SelectedServiceId == '0') {
            $('#ddlService > option').each(function () {

                ServiceIdCSV += $(this).val() + ',';
            });
        }
        else {
            ServiceIdCSV += SelectedServiceId + ',';
        }
        $("#hdfServiceId").val(ServiceIdCSV);
    }

    function SetOfferIds() {
        var SelectedServiceId = $('#ddlService').val();
        var OfferIdCSV = ',';
        if (SelectedServiceId == '0') {
            $(document.ucVendorServiceList).each(function () {
                OfferIdCSV += this.OfferId + ',';
            });
        }
        else {
            var SelectedOfferId = $('#ddlOffer').val();
            if (SelectedOfferId == "0") {
                $('#ddlOffer > option').each(function () {
                    OfferIdCSV += $(this).val() + ',';
                });
            }
            else {
                OfferIdCSV += SelectedOfferId + ',';
            }
        }
    }
</script>

Use Backend code in your web page.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ServiceList();
    }
}

public void ServiceList()
{
    ManageReport manageReport = new ManageReport();
    DataTable ServiceList = new DataTable();
    ServiceList = manageReport.GetServiceList();
    ddlService.DataSource = ServiceList;
    ddlService.DataTextField = "serviceName";
    ddlService.DataValueField = "serviceId";
    ddlService.DataBind();
    ddlService.Items.Insert(0, new ListItem("All", "0"));
}

public DataTable GetServiceList()
{
    SqlParameter[] PM = new SqlParameter[]
    {
        new SqlParameter("@Mode"    ,"Mode_Name"    ),
        new SqlParameter("@UserID"  ,UserId         )
    };
    return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", PM).Tables[0];
}

[WebMethod]
public static String GetOfferList(int UserId, String ServiceId)
{
    var sOfferList = "";
    try
    {
        CommonUtility utility = new CommonUtility();
        ManageReport manageReport = new ManageReport();
        manageReport.UserId = UserId;
        manageReport.ServiceId = ServiceId;
        DataSet dsOfferList = manageReport.GetOfferList();
        if (utility.ValidateDataSet(dsOfferList))
        {
            //DataRow dr = dsEmployerUserDepartment.Tables[0].NewRow();
            //dr[0] = "0";
            // dr[1] = "All";
            //dsEmployerUserDepartment.Tables[0].Rows.InsertAt(dr, 0);
            sOfferList = utility.ConvertToJSON(dsOfferList.Tables[0]);
        }
        return sOfferList;
    }
    catch (Exception ex)
    {
        return "Error Message: " + ex.Message;
    }
}

public DataSet GetOfferList()
{
    SqlParameter[] sqlParameter = new SqlParameter[]
        {                                                                     
            new SqlParameter("@Mode"        ,"Mode_Name"    ),
            new SqlParameter("@UserID"      ,UserId         ),
            new SqlParameter("@ServiceId"   ,ServiceId      )
        };
    return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", sqlParameter);
}

What's the default password of mariadb on fedora?

just switch your current logged-in user to the root and login without password mysql -uroot

How to use OR condition in a JavaScript IF statement?

Worth noting that || will also return true if BOTH A and B are true.

In JavaScript, if you're looking for A or B, but not both, you'll need to do something similar to:

if( (A && !B) || (B && !A) ) { ... }

Datatables - Setting column width

I set the column widths in the HTML markup like so:

    <thead>
        <tr>

            <th style='width: 5%;'>ProjectId</th>
            <th style='width: 15%;'>Title</th>
            <th style='width: 40%;'>Abstract</th>
            <th style='width: 20%;'>Keywords</th>
            <th style='width: 10%;'>PaperName</th>
            <th style='width: 10%;'>PaperURL</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.ProjectId</td>
                <td>@item.Title</td>
                <td>@item.Abstract</td>
                <td>@item.Keywords</td>
                <td>@item.PaperName</td>
                <td>@item.PaperURL</td>
            </tr>
        }
    </tbody>
</table>

Using JAXB to unmarshal/marshal a List<String>

From a personal blog post, it is not necessary to create a specific JaxbList < T > object.

Assuming an object with a list of strings:

@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}

A JAXB round trip:

public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}

Produces the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

java create date object using a value string

Here is the optimized solution to do it with SimpleDateFormat parse() method.

SimpleDateFormat formatter = new SimpleDateFormat(
        "EEEE, dd/MM/yyyy/hh:mm:ss");
String strDate = formatter.format(new Date());

try {
    Date pDate = formatter.parse(strDate);
} catch (ParseException e) { // note: parse method can throw ParseException
    e.printStackTrace();
}

Few things to notice

  • We don't need to create a Calendar instance to get the current date & time instead use new Date()
  • Also it doesn't require 2 instances of SimpleDateFormat as found in the most voted answer for this question. It's just a waste of memory
  • Furthermore, catching a generic exception like Exception is a bad practice when we know that the parse method only stands a chance to throw a ParseException. We need to be as specific as possible when dealing with Exceptions. You can refer, throws Exception bad practice?

React Router v4 - How to get current route?

In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

Export P7b file with all the certificate chain into CER file

The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.

  1. Open the .p7b in a text editor.
  2. Change the leader and trailer so the file looks similar to this:

    -----BEGIN PKCS7-----
    [... certificate content here ...]
    -----END PKCS7-----
    

For example, my StartCom certificate began with:

    -----BEGIN CERTIFICATE----- 

and ended with:

    -----END CERTIFICATE----- 
  1. Save and close the .p7b.
  2. Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):

    openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
    

The output is a .cer with the certificate chain.

Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206

how does array[100] = {0} set the entire array to 0?

Implementation is up to compiler developers.

If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

How to apply a CSS filter to a background image

This answer is for a Material Design horizontal card layout with dynamic height and an image.

To prevent distortion of the image due to the dynamic height of the card, you could use a background placeholder image with blur to adjust for changes in height.

 

Explanation

  • The card is contained in a <div> with class wrapper, which is a flexbox.
  • The card is made up of two elements, an image which is also a link, and content.
  • The link <a>, class link, is positioned relative.
  • The link consists of two sub-elements, a placeholder <div> class blur and an <img> class pic which is the clear image.
  • Both are positioned absolute and have width: 100%, but class pic has a higher stack order, i.e., z-index: 2, which places it above the placeholder.
  • The background image for the blurred placeholder is set via inline style in the HTML.

 

Code

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  width: 100%;_x000D_
  border: 1px solid rgba(0, 0, 0, 0.16);_x000D_
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16), 0 1px 1px rgba(0, 0, 0, 0.23);_x000D_
  background-color: #fff;_x000D_
  margin: 1rem auto;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.wrapper:hover {_x000D_
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);_x000D_
}_x000D_
_x000D_
.link {_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: auto;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  margin: auto;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  filter: blur(5px);_x000D_
  -webkit-filter: blur(5px);_x000D_
  -moz-filter: blur(5px);_x000D_
  -o-filter: blur(5px);_x000D_
  -ms-filter: blur(5px);_x000D_
}_x000D_
_x000D_
.pic {_x000D_
  width: calc(100% - 20px);_x000D_
  max-width: 100%;_x000D_
  height: auto;_x000D_
  margin: auto;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.pic:hover {_x000D_
  transition: all 0.2s ease-out;_x000D_
  transform: scale(1.1);_x000D_
  text-decoration: none;_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 100%;_x000D_
  max-width: 100%;_x000D_
  padding: 20px;_x000D_
  overflow-x: hidden;_x000D_
}_x000D_
_x000D_
.text {_x000D_
  margin: 0;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <a href="#" class="link">_x000D_
    <div class="blur" style="background: url('http://www.planwallpaper.com/static/assets/img/header.jpg') 50% 50% / cover;"></div>_x000D_
    <img src="http://www.planwallpaper.com/static/assets/img/header.jpg" alt="Title" class="pic" />_x000D_
  </a>_x000D_
_x000D_
  <div class="content">_x000D_
    <p class="text">Agendum dicendo memores du gi ad. Perciperem occasionem ei ac im ac designabam. Ista rom sibi vul apud tam. Notaverim to extendere expendere concilium ab. Aliae cogor tales fas modus parum sap nullo. Voluntate ingressus infirmari ex mentemque ac manifeste_x000D_
      eo. Ac gnum ei utor sive se. Nec curant contra seriem amisit res gaudet adsunt. </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

How to create a Java / Maven project that works in Visual Studio Code?

This is not a particularly good answer as it explains how to run your java code n VS Code and not necessarily a Maven project, but it worked for me because I could not get around to doing the manual configuration myself. I decided to use this method instead since it is easier and faster.

Install VSCode (and for windows, set your environment variables), then install vscode:extension/vscjava.vscode-java-pack as detailed above, and then install the code runner extension pack, which basically sets up the whole process (in the background) as explained in the accepted answer above and then provides a play button to run your java code when you're ready.

This was all explained in this video.

Again, this is not the best solution, but if you want to cut to the chase, you may find this answer useful.

How to prevent downloading images and video files from my website?

Put your image or video in flash format. Works great.

Create a table without a header in Markdown

$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
  <tbody>
    <tr>
      <td>Key 1</td>
      <td>Value 1</td>
    </tr>
    <tr>
      <td>Key 2</td>
      <td>Value 2</td>
    </tr>
  </tbody>
</table>

Sleep for milliseconds

As a Win32 replacement for POSIX systems:

void Sleep(unsigned int milliseconds) {
    usleep(milliseconds * 1000);
}

while (1) {
    printf(".");
    Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

In addition to Adam Rosenfield's answer, I would like to add that ByteBuffer.array() returns the buffer's underlying byte array, which is not necessarily "trimmed" up to the last character. Extra manipulation will be needed, such as the ones mentioned in this answer; in particular:

byte[] b = new byte[bb.remaining()]
bb.get(b);

Jump to function definition in vim

Install cscope. It works very much like ctags but more powerful. To go to definition, instead of Ctrl + ], do Ctrl + \ + g. Of course you may use both concurrently. But with a big project (say Linux kernel), cscope is miles ahead.

How to get summary statistics by group

take a look at the plyr package. Specifically, ddply

ddply(df, .(group), summarise, mean=mean(dt), sum=sum(dt))

How to set up fixed width for <td>?

None of this work for me, and have many cols on datatable to make % or sm class equals to 12 elements layout on bootstrap.

I was working with datatables Angular 5 and Bootstrap 4, and have many cols in table. The solution for me was in the TH to add a DIV element with a specific width. For example for the cols "Person Name" and "Event date" I need a specific width, then put a div in the col header, the entire col width then resizes to the width specified from the div on the TH:

<table datatable [dtOptions]="dtOptions" *ngIf="listData" class="table table-hover table-sm table-bordered text-center display" width="100%">
    <thead class="thead-dark">
        <tr>
            <th scope="col">ID </th>
            <th scope="col">Value</th>
            <th scope="col"><div style="width: 600px;">Person Name</div></th>
            <th scope="col"><div style="width: 800px;">Event date</div></th> ...

Plot correlation matrix using pandas

Form correlation matrix, in my case zdf is the dataframe which i need perform correlation matrix.

corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()

# Writing the output to a html file.
with open('test.html', 'w') as f:
   print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)

Then we can take screenshot. or convert html to an image file.

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

How to add row of data to Jtable from values received from jtextfield and comboboxes

Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

  • Set the table column headers
    1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
    2. Click on the ... button to the right of the property model. A dialog should appear.
    3. Set rows to 0, set the number of columns you want, and their names.
  • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

    1. Right-click on the button and select Events -> Action -> actionPerformed
    2. You should see code like the following auto-generated

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
      
  • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

    private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
        String data1 = something1.getSomething();
        String data2 = something2.getSomething();
        String data3 = something3.getSomething();
        String data4 = something4.getSomething();
    
        Object[] row = { data1, data2, data3, data4 };
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        model.addRow(row);
    
        // clear the entries.
    }
    

So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

What is the difference between os.path.basename() and os.path.dirname()?

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/2/library/os.path.html#os.path.basename

How to serialize Object to JSON?

One can use the Jackson library as well.

Add Maven Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId> 
  <artifactId>jackson-core</artifactId>
</dependency>

Simply do this:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );

Easiest way to split a string on newlines in .NET?

For a string variable s:

s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)

This uses your environment's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#'s escape characters \r\n.

This is a reliable solution, because if you recombine the lines with String.Join, this equals your original string:

var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);

What not to do:

  • Use StringSplitOptions.RemoveEmptyEntries, because this will break markup such as Markdown where empty lines have syntactic purpose.
  • Split on separator new char[]{Environment.NewLine}, because on Windows this will create one empty string element for each new line.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I just went through all 4 pages of this so far, and I was rather surprised that I didn't see this way to shorten a check for InvokeRequired:

using System;
using System.Windows.Forms;

/// <summary>
/// Extension methods acting on Control objects.
/// </summary>
internal static class ControlExtensionMethods
{
    /// <summary>
    /// Invokes the given action on the given control's UI thread, if invocation is needed.
    /// </summary>
    /// <param name="control">Control on whose UI thread to possibly invoke.</param>
    /// <param name="action">Action to be invoked on the given control.</param>
    public static void MaybeInvoke(this Control control, Action action)
    {
        if (control != null && control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }

    /// <summary>
    /// Maybe Invoke a Func that returns a value.
    /// </summary>
    /// <typeparam name="T">Return type of func.</typeparam>
    /// <param name="control">Control on which to maybe invoke.</param>
    /// <param name="func">Function returning a value, to invoke.</param>
    /// <returns>The result of the call to func.</returns>
    public static T MaybeInvoke<T>(this Control control, Func<T> func)
    {
        if (control != null && control.InvokeRequired)
        {
            return (T)(control.Invoke(func));
        }
        else
        {
            return func();
        }
    }
}

Usage:

myForm.MaybeInvoke(() => this.Text = "Hello world");

// Sometimes the control might be null, but that's okay.
var dialogResult = this.Parent.MaybeInvoke(() => MessageBox.Show(this, "Yes or no?", "Choice", MessageBoxButtons.YesNo));

simple way to display data in a .txt file on a webpage?

You cannot style a text file, it must be HTML

How can I use async/await at the top level?

Node -
You can run node --experimental-repl-await while in the REPL. I'm not so sure about scripting.

Deno -
Deno already has it built in.

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Styling a input type=number

Crazy idea...

You could play around with some pseudo elements, and create up/down arrows of css content hex codes. The only challange will be to precise the positioning of the arrow, but it may work:

_x000D_
_x000D_
input[type="number"] {_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.number-wrapper {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:after {_x000D_
    content: "\25B2";_x000D_
    position: absolute;_x000D_
    color: blue;_x000D_
    left: 100%;_x000D_
    margin-left: -17px;_x000D_
    margin-top: 12%;_x000D_
    font-size: 11px;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:before {_x000D_
    content: "\25BC";_x000D_
    position: absolute;_x000D_
    color: blue;_x000D_
    left: 100%;_x000D_
    bottom: 0;_x000D_
    margin-left: -17px;_x000D_
    margin-bottom: -14%;_x000D_
    font-size: 11px;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

How do I output an ISO 8601 formatted string in JavaScript?

The problem with toISOString is that it gives datetime only as "Z".

ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).

I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.



    var timezone_offset_min = new Date().getTimezoneOffset(),
        offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
        offset_min = Math.abs(timezone_offset_min%60),
        timezone_standard;

    if(offset_hrs < 10)
        offset_hrs = '0' + offset_hrs;

    if(offset_min > 10)
        offset_min = '0' + offset_min;

    // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
    // So add an opposite sign to the offset
    // If offset is 0, it means timezone is UTC
    if(timezone_offset_min < 0)
        timezone_standard = '+' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min > 0)
        timezone_standard = '-' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min == 0)
        timezone_standard = 'Z';

    // Timezone difference in hours and minutes
    // String such as +5:30 or -6:00 or Z
    console.log(timezone_standard); 


Once you have the timezone offset in hours and minutes, you can append to a datetime string.

I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

View markdown files offline

Remarkable, certainly a great tool.

Features:

  • Live preview
  • It's free.
  • Extremely lightweight
  • Export to HTML, PDF

Download: https://remarkableapp.github.io/

INSERT IF NOT EXISTS ELSE UPDATE?

You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:

CREATE TABLE data   (id INTEGER PRIMARY KEY, event_id INTEGER, track_id INTEGER, value REAL);
CREATE UNIQUE INDEX data_idx ON data(event_id, track_id);

Then you can issue:

INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

The "SELECT * FROM data" will give you:

2|2|2|3.0
3|1|2|5.0

Note that the data.id is "3" and not "1" because REPLACE does a DELETE and INSERT, not an UPDATE. This also means that you must ensure that you define all necessary columns or you will get unexpected NULL values.

How can I get query parameters from a URL in Vue.js?

More detailed answer to help the newbies of VueJS:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)

And the code itself:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

Trigger change event of dropdown

I don't know that much JQuery but I've heard it allows to fire native events with this syntax.

$(document).ready(function(){

    $('#countrylist').change(function(e){
       // Your event handler
    });

    // And now fire change event when the DOM is ready
    $('#countrylist').trigger('change');
});

You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.

More information here.

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

PostgreSQL Crosstab Query

Install the additional module tablefunc once per database, which provides the function crosstab(). Since Postgres 9.1 you can use CREATE EXTENSION for that:

CREATE EXTENSION IF NOT EXISTS tablefunc;

Improved test case

CREATE TABLE tbl (
   section   text
 , status    text
 , ct        integer  -- "count" is a reserved word in standard SQL
);

INSERT INTO tbl VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                    , ('C', 'Inactive', 7);  -- ('C', 'Active') is missing

Simple form - not fit for missing attributes

crosstab(text) with 1 input parameter:

SELECT *
FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- needs to be "ORDER BY 1,2" here
   ) AS ct ("Section" text, "Active" int, "Inactive" int);

Returns:

 Section | Active | Inactive
---------+--------+----------
 A       |      1 |        2
 B       |      4 |        5
 C       |      7 |           -- !!
  • No need for casting and renaming.
  • Note the incorrect result for C: the value 7 is filled in for the first column. Sometimes, this behavior is desirable, but not for this use case.
  • The simple form is also limited to exactly three columns in the provided input query: row_name, category, value. There is no room for extra columns like in the 2-parameter alternative below.

Safe form

crosstab(text, text) with 2 input parameters:

SELECT *
FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- could also just be "ORDER BY 1" here

  , $$VALUES ('Active'::text), ('Inactive')$$
   ) AS ct ("Section" text, "Active" int, "Inactive" int);

Returns:

 Section | Active | Inactive
---------+--------+----------
 A       |      1 |        2
 B       |      4 |        5
 C       |        |        7  -- !!
  • Note the correct result for C.

  • The second parameter can be any query that returns one row per attribute matching the order of the column definition at the end. Often you will want to query distinct attributes from the underlying table like this:

    'SELECT DISTINCT attribute FROM tbl ORDER BY 1'
    

    That's in the manual.

    Since you have to spell out all columns in a column definition list anyway (except for pre-defined crosstabN() variants), it is typically more efficient to provide a short list in a VALUES expression like demonstrated:

    $$VALUES ('Active'::text), ('Inactive')$$)
    

    Or (not in the manual):

    $$SELECT unnest('{Active,Inactive}'::text[])$$  -- short syntax for long lists
    
  • I used dollar quoting to make quoting easier.

  • You can even output columns with different data types with crosstab(text, text) - as long as the text representation of the value column is valid input for the target type. This way you might have attributes of different kind and output text, date, numeric etc. for respective attributes. There is a code example at the end of the chapter crosstab(text, text) in the manual.

db<>fiddle here

Advanced examples


\crosstabview in psql

Postgres 9.6 added this meta-command to its default interactive terminal psql. You can run the query you would use as first crosstab() parameter and feed it to \crosstabview (immediately or in the next step). Like:

db=> SELECT section, status, ct FROM tbl \crosstabview

Similar result as above, but it's a representation feature on the client side exclusively. Input rows are treated slightly differently, hence ORDER BY is not required. Details for \crosstabview in the manual. There are more code examples at the bottom of that page.

Related answer on dba.SE by Daniel Vérité (the author of the psql feature):



The previously accepted answer is outdated.

  • The variant of the function crosstab(text, integer) is outdated. The second integer parameter is ignored. I quote the current manual:

    crosstab(text sql, int N) ...

    Obsolete version of crosstab(text). The parameter N is now ignored, since the number of value columns is always determined by the calling query

  • Needless casting and renaming.

  • It fails if a row does not have all attributes. See safe variant with two input parameters above to handle missing attributes properly.

  • ORDER BY is required in the one-parameter form of crosstab(). The manual:

    In practice the SQL query should always specify ORDER BY 1,2 to ensure that the input rows are properly ordered

CURL to access a page that requires a login from a different page

Also you might want to log in via browser and get the command with all headers including cookies:

Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".

screenshot

Git log out user from command line

I was not able to clone a repository due to have logged on with other credentials.

To switch to another user, I >>desperate<< did:

git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper

after, instead using ssh link, I used HTTPS link. It asked for credentials and it worked fine FOR ME!

Best XML Parser for PHP

It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.

If you are looking to manipulate the XML files you're probably best off using DOM XML

Get absolute path of initially run script

realpath($_SERVER['SCRIPT_FILENAME'])

For script run under web server $_SERVER['SCRIPT_FILENAME'] will contain the full path to the initially called script, so probably your index.php. realpath() is not required in this case.

For the script run from console $_SERVER['SCRIPT_FILENAME'] will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.

What's the difference between a Future and a Promise?

(I'm not completely happy with the answers so far, so here is my attempt...)

I think that Kevin Wright's comment ("You can make a Promise and it's up to you to keep it. When someone else makes you a promise you must wait to see if they honour it in the Future") summarizes it pretty well, but some explanation can be useful.

Futures and promises are pretty similar concepts, the difference is that a future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once). The Java 8 CompletableFuture and the Guava SettableFuture can be thought of as promises, because their value can be set ("completed"), but they also implement the Future interface, therefore there is no difference for the client.

The result of the future will be set by "someone else" - by the result of an asynchronous computation. Note how FutureTask - a classic future - must be initialized with a Callable or Runnable, there is no no-argument constructor, and both Future and FutureTask are read-only from the outside (the set methods of FutureTask are protected). The value will be set to the result of the computation from the inside.

On the other hand, the result of a promise can be set by "you" (or in fact by anybody) anytime because it has a public setter method. Both CompletableFuture and SettableFuture can be created without any task, and their value can be set at any time. You send a promise to the client code, and fulfill it later as you wish.

Note that CompletableFuture is not a "pure" promise, it can be initialized with a task just like FutureTask, and its most useful feature is the unrelated chaining of processing steps.

Also note that a promise does not have to be a subtype of future and it does not have to be the same object. In Scala a Future object is created by an asynchronous computation or by a different Promise object. In C++ the situation is similar: the promise object is used by the producer and the future object by the consumer. The advantage of this separation is that the client cannot set the value of the future.

Both Spring and EJB 3.1 have an AsyncResult class, which is similar to the Scala/C++ promises. AsyncResult does implement Future but this is not the real future: asynchronous methods in Spring/EJB return a different, read-only Future object through some background magic, and this second "real" future can be used by the client to access the result.

Git Bash is extremely slow on Windows 7 x64

In an extension to Chris Dolan's answer, I used the following alternative PS1 setting. Simply add the code fragment to your ~/.profile (on Windows 7: C:/Users/USERNAME/.profile).

fast_git_ps1 ()
{
    printf -- "$(git branch 2>/dev/null | sed -ne '/^\* / s/^\* \(.*\)/ [\1] / p')"
}

PS1='\[\033]0;$MSYSTEM:\w\007
\033[32m\]\u@\h \[\033[33m\w$(fast_git_ps1)\033[0m\]
$ '

This retains the benefit of a colored shell and display of the current branch name (if in a Git repository), but it is significantly faster on my machine, from ~0.75 s to 0.1 s.

This is based on this blog post.

How can I extract audio from video with ffmpeg?

To encode mp3 audio ffmpeg.org shows the following example:

ffmpeg -i input.wav -codec:a libmp3lame -qscale:a 2 output.mp3

I extracted the audio from a video just by replacing input.wav with the video filename. The 2 means 190 kb/sec. You can see the other quality levels at my link above.

MySQL: determine which database is selected?

SELECT DATABASE() worked in PHPMyAdmin.

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

Importing a function from a class in another file?

from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()  
# if you want to return run itself to be used later
return theclass.run

Change the end of comm system to:

if __name__ == '__main__':
    a_game = Comm_system()
    a_game.run()

It's those lines being always run that are causing it to be run when imported as well as when executed.

Convert array of strings into a string in Java

Use Apache Commons' StringUtils library's join method.

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");

Set a button group's width to 100% and make buttons equal width?

BOOTSTRAP 2 (source)

The problem is that there is no width set on the buttons. Try this:

.btn {width:20%;}

EDIT:

By default the buttons take an auto width of its text length plus some padding, so I guess for your example it is probably more like 14.5% for 5 buttons (to compensate for the padding).

Note:

If you don't want to try and compensate for padding you can use box-sizing:border-box;

http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Find Item in ObservableCollection without using a loop

Consider creating an index. A dictionary can do the trick. If you need the list semantics, subclass and keep the index as a private member...

Why use $_SERVER['PHP_SELF'] instead of ""

In addition to above answers, another way of doing it is $_SERVER['PHP_SELF'] or simply using an empty string is to use __DIR__.
OR
If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
Both returns the folder name of the file in context.

EDIT
As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF']) can return the folder name of the file in context.

Combination of async function + await + setTimeout

Made a util inspired from Dave's answer

Basically passed in a done callback to call when the operation is finished.

// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
  cb(resolve);
  setTimeout(() => reject('Request is taking too long to response'), timeout);
});

This is how I use it:

try {
  await setAsyncTimeout(async done => {
    const requestOne = await someService.post(configs);
    const requestTwo = await someService.get(configs);
    const requestThree = await someService.post(configs);
    done();
  }, 5000); // 5 seconds max for this set of operations
}
catch (err) {
  console.error('[Timeout] Unable to complete the operation.', err);
}

File Upload in WebView

Working Method from HONEYCOMB (API 11) to Oreo(API 27)
[Not Tested on Pie 9.0]

static WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;

Modified onActivityResult()

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        if (requestCode == REQUEST_SELECT_FILE)
        {
            if (uploadMessage == null)
                return;
            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
            uploadMessage = null;
        }
    }
    else if (requestCode == FILECHOOSER_RESULTCODE)
    {
        if (null == mUploadMessage)
            return;
    // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
    // Use RESULT_OK only if you're implementing WebView inside an Activity
        Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }
    else
        Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}

Now in onCreate() or onCreateView() paste the following code

    WebSettings mWebSettings = mWebView.getSettings();
    mWebSettings.setJavaScriptEnabled(true);
    mWebSettings.setSupportZoom(false);
    mWebSettings.setAllowFileAccess(true);
    mWebSettings.setAllowContentAccess(true);

mWebView.setWebChromeClient(new WebChromeClient()
{
    // For 3.0+ Devices (Start)
    // onActivityResult attached before constructor
    protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
    {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
    }
   

    // For Lollipop 5.0+ Devices
    public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
    {
        if (uploadMessage != null) {
            uploadMessage.onReceiveValue(null);
            uploadMessage = null;
        }

        uploadMessage = filePathCallback;

        Intent intent = fileChooserParams.createIntent();
        try
        {
            startActivityForResult(intent, REQUEST_SELECT_FILE);
        } catch (ActivityNotFoundException e)
        {
            uploadMessage = null;
            Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    
    //For Android 4.1 only
    protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
    {
        mUploadMessage = uploadMsg;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
    }

    protected void openFileChooser(ValueCallback<Uri> uploadMsg)
    {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }
});

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

Java: how do I check if a Date is within a certain range?

Consider using Joda Time. I love this library and wish it would replace the current horrible mess that are the existing Java Date and Calendar classes. It's date handling done right.

EDIT: It's not 2009 any more, and Java 8's been out for ages. Use Java 8's built in java.time classes which are based on Joda Time, as Basil Bourque mentions above. In this case you'll want the Period class, and here's Oracle's tutorial on how to use it.

How to run ~/.bash_profile in mac terminal

On MacOS: add source ~/.bash_profile to the end of ~/.zshrc. Then this profile will be in effect when you open zsh.

Extracting text OpenCV

You can try this method that is developed by Chucai Yi and Yingli Tian.

They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:

Note: to make the result more robust, you can further merge adjacent boxes together.


Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.

With this, you can get recognized texts like:

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

Importing a GitHub project into Eclipse

As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in

Copy the URL from GitHub and select in Eclipse from the menu the

File ? Import ? Git ? Projects from Git

http://wiki.eclipse.org/images/5/5a/Egit-0.9-import-projects-select-repository.png


If the Git repo isn't cloned yet:

In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import), select Git => Projects from Git and click Next.
Select “URI” and click Next.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next. If you use GitHub, you can copy the URI from the web page.

Select all branches you wish to clone and hit Next again.

Hit the Clone… button to open another wizard for cloning Git repositories.

http://eclipsesource.com/blogs/wp-content/uploads/2012/12/14-282x300.png


Original answer (July 2011)

First, if your "Working Directory" is C:\Users, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git directory in C:\Users)

Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName".

As described in the EGit user Manual page:

In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git" and often referred to as ".git-folder". It contains the actual repository (i.e. the Commits, the References, the logs and such).

The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.

Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:

See also the Using EGit with Github section.


My working directory is now c:\users\projectname\.git

You should have the content of that repo checked out in c:\users\projectname (in other words, you should have more than just the .git).

So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.

That is normal.

If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.

Again normal.

When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

No, that would only create an empty project.
If that project is created in c:\users\projectname, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".

You could also use the "Import existing project" option, if your GitHub repo had versioned the .project and .classpath file, but that may not be the case here.

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

In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.

Then you can use anything in that assembly.

How to detect the physical connected state of a network cable/connector?

You can use ifconfig.

# ifconfig eth0 up
# ifconfig eth0

If the entry shows RUNNING, the interface is physically connected. This will be shown regardless if the interface is configured.

This is just another way to get the information in /sys/class/net/eth0/operstate.

returning a Void object

Just for the sake of it, there is of course the possibility to create Void instance using reflection:

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something

        try {
            Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
            voidConstructor.setAccessible(true);
            return voidConstructor.newInstance();
        } catch (Exception ex) {
            // Rethrow, or return null, or whatever.
        }
    }
}

You probably won't do that in production.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

The one with no extra imports!

Their is a pythonic standard called EAFP(Easier to Ask for Forgiveness than Permission). Below code is based on that python standard.

# The A and B dictionaries
A = {'a': 1, 'b': 2, 'c': 3}
B = {'b': 3, 'c': 4, 'd': 5}

# The final dictionary. Will contain the final outputs.
newdict = {}

# Make sure every key of A and B get into the final dictionary 'newdict'.
newdict.update(A)
newdict.update(B)

# Iterate through each key of A.
for i in A.keys():

    # If same key exist on B, its values from A and B will add together and
    # get included in the final dictionary 'newdict'.
    try:
        addition = A[i] + B[i]
        newdict[i] = addition

    # If current key does not exist in dictionary B, it will give a KeyError,
    # catch it and continue looping.
    except KeyError:
        continue

EDIT: thanks to jerzyk for his improvement suggestions.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

When you got:

Error: Uncaught Error: Target container is not a DOM element.

You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function(event) {
  ReactDOM.render(<App />, document.getElementById('root'));
})

Can I check if Bootstrap Modal Shown / Hidden?

Here's some custom modal code that gives the modal states more explicitly named classes:

$('.modal').on('show.bs.modal', function(e)
{
    e.currentTarget.classList.add("modal-fading-in");
    e.currentTarget.classList.remove("modal-fading-out");
    e.currentTarget.classList.remove("modal-hidden");
    e.currentTarget.classList.remove("modal-visible");
});

$('.modal').on('hide.bs.modal', function(e)
{
    e.currentTarget.classList.add("modal-fading-out");
    e.currentTarget.classList.remove("modal-fading-in");
    e.currentTarget.classList.remove("modal-hidden");
    e.currentTarget.classList.remove("modal-visible");
});

$('.modal').on('hidden.bs.modal', function(e)
{
    e.currentTarget.classList.add("modal-hidden");
    e.currentTarget.classList.remove("modal-fading-in");
    e.currentTarget.classList.remove("modal-fading-out");
    e.currentTarget.classList.remove("modal-visible");
});

$('.modal').on('shown.bs.modal', function(e)
{
    e.currentTarget.classList.add("modal-visible");
    e.currentTarget.classList.remove("modal-fading-in");
    e.currentTarget.classList.remove("modal-fading-out");
    e.currentTarget.classList.remove("modal-hidden");
});

You can then easily target the modal's various states with both JS and CSS.

JS example:

if (document.getElementById('myModal').hasClass('modal-fading-in'))
{
    console.log("The modal is currently fading in. Please wait.");
}

CSS example:

.modal-fading-out, .modal-hidden
{
    opacity: 0.5;
}

Programmatically Install Certificate into Mozilla

Here is an alternative way that doesn't override the existing certificates: [bash fragment for linux systems]

certificateFile="MyCa.cert.pem"
certificateName="MyCA Name" 
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert8.db")
do
  certDir=$(dirname ${certDB});
  #log "mozilla certificate" "install '${certificateName}' in ${certDir}"
  certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d ${certDir}
done

You may find certutil in the libnss3-tools package (debian/ubuntu).

Source:
http://web.archive.org/web/20150622023251/http://www.computer42.org:80/xwiki-static/exported/DevNotes/xwiki.DevNotes.Firefox.html

See also:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil

Difference between object and class in Scala

As has been explained by many, object defines a singleton instance. The one thing in the answers here that I believe is left out is that object serves several purposes.

  • It can be the companion object to a class/trait, containing what might be considered static methods or convenience methods.

  • It can act much like a module, containing related/subsidiary types and definitions, etc.

  • It can implement an interface by extending a class or one or more traits.

  • It can represent a case of a sealed trait that contains no data. In this respect, it's often considered more correct than a case class with no parameters. The special case of a sealed trait with only case object implementors is more or less the Scala version of an enum.

  • It can act as evidence for implicit-driven logic.

  • It introduces a singleton type.

It's a very powerful and general construct. What can be very confusing to Scala beginners is that the same construct can have vastly different uses. And an object can serve many of these different uses all at once, which can be even more confusing.

android: how to change layout on button click?

I know I'm coming to this late, but what the heck.

I've got almost the exact same code as Kris, using just one Activity but with 2 different layouts/views, and I want to switch between the layouts at will.

As a test, I added 2 menu options, each one switches the view:

public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.item1:
                setContentView(R.layout.main);
                return true;
            case R.id.item2:
                setContentView(R.layout.alternate);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Note, I've got one Activity class. This works perfectly. So I have no idea why people are suggesting using different Activities / Intents. Maybe someone can explain why my code works and Kris's didn't.

Insert variable into Header Location PHP

Try using double quotes and keeping the L in location lowercase...

header("location: http://linkhere.com/HERE_I_WANT_THE_VARIABLE");

or for example

header("location: http://linkhere.com/$variable");

No need to concatenate here to insert variables.

Check if registry key exists using VBScript

In case anyone else runs into this, I took WhoIsRich's example and modified it a bit. When calling ReadReg I needed to do the following: ReadReg("App", "HKEY_CURRENT_USER\App\Version") which would then be able to read the version number from the registry, if it existed. I also am using HKCU since it does not require admin privileges to write to.

Function ReadReg(RegKey, RegPath)
      Const HKEY_CURRENT_USER = &H80000001
      Dim objRegistry, oReg
      Set objRegistry = CreateObject("Wscript.shell")
      Set oReg = GetObject("winmgmts:!root\default:StdRegProv")

      if oReg.EnumKey(HKEY_CURRENT_USER, RegKey) = 0 Then
        ReadReg = objRegistry.RegRead(RegPath)
      else
        ReadReg = ""
      end if
End Function

How do I fetch lines before/after the grep result in bash?

Try this:

grep -i -A 10 "my_regex"

-A 10 means, print ten lines after match to "my_regex"

Laravel - Form Input - Multiple select for a one to many relationship

This might be a better approach than top answer if you need to compare 2 output arrays to each other but use the first array to populate the options.

This is also helpful when you have a non-numeric or offset index (key) in your array.

<select name="roles[]" multiple>
    @foreach($roles as $key => $value)
        <option value="{{$key}}" @if(in_array($value, $compare_roles))selected="selected"@endif>
            {{$value}}
        </option>
    @endforeach
</select>

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

The application was unable to start correctly (0xc000007b)

I just ran into this issue. I searched for "C++" under my "Apps & Features" in Windows 10 control panel and noticed that some kind of update had just run a few days prior and installed VC++ Redistributable 2012-2017. The app that was running into the error message only required VC++ 2010. I uninstalled all of them and then reinstalled just 2010 x86/x64, and the error went away and the application functioned as expected.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of text like in a messenger

 >>> stex[40]
 array(['Know the famous thing ...

and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:

 >>> stex = (df5.ix[0:,[11]]).values
 >>> a_str = ','.join(str(x) for x in stex)
 >>> a_str = a_str.split()
 >>> fd2 = nltk.FreqDist(a_str)
 >>> fd2.most_common(50)

Add button to navigationbar programmatically

UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);

UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
     forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];

UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];

///// called event

-(IBAction)Back_btn:(id)sender
{
    //Your code here
}

SWIFT:

var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)

var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true

var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton

func back_btn(_ sender: Any) {
    //Your code here
}

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

You can do it with SQL Management Studio -

Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

Here is the msdn source - http://msdn.microsoft.com/en-us/library/ms188670.aspx

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

Are PDO prepared statements sufficient to prevent SQL injection?

Eaven if you are going to prevent sql injection front-end, using html or js checks, you'd have to consider that front-end checks are "bypassable".

You can disable js or edit a pattern with a front-end development tool (built in with firefox or chrome nowadays).

So, in order to prevent SQL injection, would be right to sanitize input date backend inside your controller.

I would like to suggest to you to use filter_input() native PHP function in order to sanitize GET and INPUT values.

If you want to go ahead with security, for sensible database queries, I'd like to suggest to you to use regular expression to validate data format. preg_match() will help you in this case! But take care! Regex engine is not so light. Use it only if necessary, otherwise your application performances will decrease.

Security has a costs, but do not waste your performance!

Easy example:

if you want to double check if a value, received from GET is a number, less then 99 if(!preg_match('/[0-9]{1,2}/')){...} is heavyer of

if (isset($value) && intval($value)) <99) {...}

So, the final answer is: "No! PDO Prepared Statements does not prevent all kind of sql injection"; It does not prevent unexpected values, just unexpected concatenation

hasNext in Python iterators?

No. The most similar concept is most likely a StopIteration exception.

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

PHP Remove elements from associative array

Try this:

$keys = array_keys($array, "Completed");

/edit As mentioned by JohnP, this method only works for non-nested arrays.

C# Numeric Only TextBox Control

From C#3.5 I assume you're using WPF.

Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.

For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.

Look up Binding on MSDN.

How do I trap ctrl-c (SIGINT) in a C# console app

The Console.CancelKeyPress event is used for this. This is how it's used:

public static void Main(string[] args)
{
    Console.CancelKeyPress += delegate {
        // call methods to clean up
    };

    while (true) {}
}

When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.

There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };

        while (MainClass.keepRunning) {
            // Do your work in here, in small chunks.
            // If you literally just want to wait until ctrl-c,
            // not doing anything, see the answer using set-reset events.
        }
        Console.WriteLine("exited gracefully");
    }
}

The difference between this code and the first example is that e.Cancel is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens the keepRunning variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.

Add leading zeroes/0's to existing Excel values to certain length

The more efficient (less obtrusive) way of doing this is through custom formatting.

  1. Highlight the column/array you want to style.
  2. Click ctrl + 1 or Format -> Format Cells.
  3. In the Number tab, choose Custom.
  4. Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

MemoryStream - Cannot access a closed Stream

In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):

PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);

The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

setup android on eclipse but don't know SDK directory

Late to the conversion...

For me, I found this at:

C:\Program Files (x86)\Android\android-sdk

This is the default location for Windows 64-bit.

Also, try to recall some of your default locations when not presented with some suggestions.

jQuery add image inside of div tag

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

iOS: Multi-line UILabel in Auto Layout

Expand your label set number of lines to 0 and also more importantly for auto layout set height to >= x. Auto layout will do the rest. You may also contain your other elements based on previous element to correctly position then.

auto layout

Select SQL results grouped by weeks

the provided solutions seem a little complex? this might help:

https://msdn.microsoft.com/en-us/library/ms174420.aspx

select
   mystuff,
   DATEPART ( year, MyDateColumn ) as yearnr,
   DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

ArrayList vs List<> in C#

To add to the above points. Using ArrayList in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T> will use much low memory than the ArrayList.

for example if we use a ArrayList of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int> of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.

Source: ArrayList’s vs. generic List for primitive types and 64-bits

Call an activity method from a fragment

Here is how I did this:

first make interface

interface NavigationInterface {
    fun closeActivity()
}

next make sure activity implements interface and overrides interface method(s)

class NotesActivity : AppCompatActivity(), NavigationInterface {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notes)
        setSupportActionBar(findViewById(R.id.toolbar))
    }

    override fun closeActivity() {
        this.finish()
    }
}

then make sure to create interface listener in fragment

private lateinit var navigationInterface: NavigationInterface

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    //establish interface communication
    activity?.let {
        instantiateNavigationInterface(it)
    }
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_notes_info, container, false)
}

private fun instantiateNavigationInterface(context: FragmentActivity) {
    navigationInterface = context as NavigationInterface
}

then you can make calls like such:

view.findViewById<Button>(R.id.button_second).setOnClickListener {
    navigationInterface.closeActivity()
}

jQuery.click() vs onClick

<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />

onclick, onmouseover, onmouseout, etc. events are actually bad for performance (in Internet Explorer mainly, go figure). If you code using Visual Studio, when you run a page with these, every single one of these will create a separate SCRIPT block taking up memory, and thus slowing down performance.

Not to mention you should have a separation of concerns: JavaScript and layouts should be separated!

It is always better to create evenHandlers for any of these events, one event can capture hundreds/thousands of items, instead of creating thousands of separate script blocks for each one!

(Also, everything everyone else is saying.)

How do I add indices to MySQL tables?

Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.

Explanation

Primary key as index

Consider you have a tbl_student table and you want student_id as primary key:

ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)

Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.

Specify index name

ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)

Above statement will create an ordinary index with student_index name.

Create unique index

ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)

Here, student_unique_index is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).

Fulltext option

ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)

Above statement will create the Fulltext index name with student_fulltext_index, for which you need MyISAM Mysql Engine.

How to remove indexes ?

DROP INDEX `student_index` ON `tbl_student`

How to check available indexes?

SHOW INDEX FROM `tbl_student`

Eclipse Problems View not showing Errors anymore

My mistake was that I was creating classes in resource package...

Creating classes in src/main/java solved the issue.

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)

How to overlay images

Unless you use the <img> tag, which displays an image by itself, you will not be able to achieve this with pure CSS alone. You will also need TWO HTML elements as well - one for each picture. This is because the only way you can make an element display a picture via CSS is with the background-image property, and every element can have only one background image. Which two elements you choose and how you position them is up to you. There are many ways how you can position one HTML element above another.

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

How does the vim "write with sudo" trick work?

:w - Write a file.

!sudo - Call shell sudo command.

tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):

tutorial link

Is there a "null coalescing" operator in JavaScript?

beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript. 1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object
  1. Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

Call Stored Procedure within Create Trigger in SQL Server

I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.

ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
    AFTER INSERT
AS
        -- This is your primary key.  I assume INT, but initialize
        -- to minimum value for the type you are using.
        DECLARE @rAgent_ID INT = 0

        -- Looping variable.
        DECLARE @i INT = 0

        -- Count of rows affected for looping over
        DECLARE @count INT

        -- These are your old variables.
        DECLARE @rAgent_Name NVARCHAR(50)
        DECLARE @rAgent_Email NVARCHAR(50)
        DECLARE @rAgent_IP NVARCHAR(50)
        DECLARE @hotelID INT
        DECLARE @retval INT

    BEGIN 
        SET NOCOUNT ON ;

        -- Get count of affected rows
        SELECT  @Count = Count(rAgent_ID)
        FROM    inserted

        -- Loop over rows affected
        WHILE @i < @count
            BEGIN
                -- Get the next rAgent_ID
                SELECT TOP 1
                        @rAgent_ID = rAgent_ID
                FROM    inserted
                WHERE   rAgent_ID > @rAgent_ID
                ORDER BY rAgent_ID ASC

                -- Populate values for the current row
                SELECT  @rAgent_Name = rAgent_Name,
                        @rAgent_Email = rAgent_Email,
                        @rAgent_IP = rAgent_IP,
                        @hotelID = hotelID
                FROM    Inserted
                WHERE   rAgent_ID = @rAgent_ID

                -- Run your stored procedure
                EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
                    @rAgent_IP, @hotelID, 'RA', @retval 

                -- Set up next iteration
                SET @i = @i + 1
            END
    END 
GO

I sure hope this helps you out. Cheers!

What's the syntax for mod in java

In Java, the mod operation can be performed as such:

Math.floorMod(a, b)

Note: The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:

a % b

C# removing items from listbox

You can use following code too:

 foreach (var item in listBox1.Items.Cast<string>().ToList())
 {
     string removelistitem = "OBJECT";
     if (item.Contains(removelistitem))
     {
        listBox1.Items.Remove(item);
     }
 }

CSS: Center block, but align contents to the left

Is this what you are looking for? Flexbox...

_x000D_
_x000D_
.container{_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
.inside{_x000D_
  height:100px;_x000D_
  width:100px;_x000D_
  background:gray;_x000D_
  border:1px solid;_x000D_
}
_x000D_
<section class="container">_x000D_
  <section class="inside">_x000D_
    A_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    B_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    C_x000D_
  </section>_x000D_
</section>
_x000D_
_x000D_
_x000D_

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

Understanding checked vs unchecked exceptions in Java

In short, exceptions which your module or modules above are supposed to handle during runtime are called checked exceptions; others are unchecked exceptions which are either RuntimeException or Error.

In this video, it explains checked and unchecked exceptions in Java:
https://www.youtube.com/watch?v=ue2pOqLaArw

Java: parse int value from a char

Try the following:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

if u subtract by char '0', the ASCII value needs not to be known.

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

document.createElement("script") synchronously

Ironically, I have what you want, but want something closer to what you had.

I am loading things in dynamically and asynchronously, but with an load callback like so (using dojo and xmlhtpprequest)

  dojo.xhrGet({
    url: 'getCode.php',
    handleAs: "javascript",
    content : {
    module : 'my.js'
  },
  load: function() {
    myFunc1('blarg');
  },
  error: function(errorMessage) {
    console.error(errorMessage);
  }
});

For a more detailed explanation, see here

The problem is that somewhere along the line the code gets evaled, and if there's anything wrong with your code, the console.error(errorMessage); statement will indicate the line where eval() is, not the actual error. This is SUCH a big problem that I am actually trying to convert back to <script> statements (see here.

Update R using RStudio

Paste this into the console and run the commands:

## How to update R in RStudio using installr package (for Windows)
## paste this into the console and run the commands
## "The updateR() command performs the following: finding the latest R version, downloading it, running the installer, deleting the installation file, copy and updating old packages to the new R installation."
## more info here: https://cran.r-project.org/web/packages/installr/index.html

install.packages("installr")
library(installr)
updateR()

## Watch for small pop up windows. There will be many questions and they don't always pop to the front. 
## Note: It warns that it might work better in Rgui but I did it in Rstudio and it worked just fine. 

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

Node JS Error: ENOENT

"/tmp/test.jpg" is not the correct path – this path starts with / which is the root directory.

In unix, the shortcut to the current directory is .

Try this "./tmp/test.jpg"

What is a singleton in C#?

It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

You should use it if you want a class that can only be instanciated once.

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

As many others have pointed out here, increasing the timeout settings for NGINX can solve your issue.

However, increasing your timeout settings might not be as straightforward as many of these answers suggest. I myself faced this issue and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This did not help me a single bit; there was no apparent change in NGINX' timeout settings. Now, many hours later, I finally managed to fix this problem.

The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The following example should demonstrate the difference:

String destroyTheWorld() {
  // destroy the world logic
  return "successfully destroyed the world";
}

Optional<String> opt = Optional.of("Save the world");

// we're dead
opt.orElse(destroyTheWorld());

// we're safe    
opt.orElseGet(() -> destroyTheWorld());

The answer appears in the docs as well.

public T orElseGet(Supplier<? extends T> other):

Return the value if present, otherwise invoke other and return the result of that invocation.

The Supplier won't be invoked if the Optional presents. whereas,

public T orElse(T other):

Return the value if present, otherwise return other.

If other is a method that returns a string, it will be invoked, but it's value won't be returned in case the Optional exists.

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

The change event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)

Consider the following code:

$('input[name="job[video_need]"]').on('change', function () {
    var value;
    if ($(this).val() == 'none') {
        value = 'hide';
    } else {
        value = 'show';
    }
    $('#video-script-collapse').collapse(value);
});

I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.

java: Class.isInstance vs Class.isAssignableFrom

For brevity, we can understand these two APIs like below:

  1. X.class.isAssignableFrom(Y.class)

If X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

  1. X.class.isInstance(y)

Say y is an instance of class Y, if X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

How to configure Eclipse build path to use Maven dependencies?

None of that solved my problem. but what I did was if click on the pom.xml, there is a tab at the bottom named dependencies. in this tab it is split into 2 section, one called dependencies and one called dependency management. select every thing in the dependency section and click add to be under the dependency management control. close and reopen your project.

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Receiver not registered exception error?

Be careful, when you register by

LocalBroadcastManager.getInstance(this).registerReceiver()

you can't unregister by

 unregisterReceiver()

you must use

LocalBroadcastManager.getInstance(this).unregisterReceiver()

or app will crash, log as follow:

09-30 14:00:55.458 19064-19064/com.jialan.guangdian.view E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jialan.guangdian.view, PID: 19064 java.lang.RuntimeException: Unable to stop service com.google.android.exoplayer.demo.player.PlayService@141ba331: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.ActivityThread.handleStopService(ActivityThread.java:2941) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:769) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1794) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:510) at com.google.android.exoplayer.demo.player.PlayService.onDestroy(PlayService.java:542) at android.app.ActivityThread.handleStopService(ActivityThread.java:2924) at android.app.ActivityThread.access$2200(ActivityThread.java:148)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5310)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 

Submitting a form by pressing enter without a submit button

This is my solution, tested in Chrome, Firefox 6 and IE7+:

.hidden{
    height: 1px;
    width: 1px;
    position: absolute;
    z-index: -100;
}

Catch a thread's exception in the caller thread in Python

pygolang provides sync.WorkGroup which, in particular, propagates exception from spawned worker threads to the main thread. For example:

#!/usr/bin/env python
"""This program demostrates how with sync.WorkGroup an exception raised in
spawned thread is propagated into main thread which spawned the worker."""

from __future__ import print_function
from golang import sync, context

def T1(ctx, *argv):
    print('T1: run ... %r' % (argv,))
    raise RuntimeError('T1: problem')

def T2(ctx):
    print('T2: ran ok')

def main():
    wg = sync.WorkGroup(context.background())
    wg.go(T1, [1,2,3])
    wg.go(T2)

    try:
        wg.wait()
    except Exception as e:
        print('Tmain: caught exception: %r\n' %e)
        # reraising to see full traceback
        raise

if __name__ == '__main__':
    main()

gives the following when run:

T1: run ... ([1, 2, 3],)
T2: ran ok
Tmain: caught exception: RuntimeError('T1: problem',)

Traceback (most recent call last):
  File "./x.py", line 28, in <module>
    main()
  File "./x.py", line 21, in main
    wg.wait()
  File "golang/_sync.pyx", line 198, in golang._sync.PyWorkGroup.wait
    pyerr_reraise(pyerr)
  File "golang/_sync.pyx", line 178, in golang._sync.PyWorkGroup.go.pyrunf
    f(pywg._pyctx, *argv, **kw)
  File "./x.py", line 10, in T1
    raise RuntimeError('T1: problem')
RuntimeError: T1: problem

The original code from the question would be just:

    wg = sync.WorkGroup(context.background())

    def _(ctx):
        shul.copytree(sourceFolder, destFolder)
    wg.go(_)

    # waits for spawned worker to complete and, on error, reraises
    # its exception on the main thread.
    wg.wait()

How to specify the default error page in web.xml?

On Servlet 3.0 or newer you could just specify

<web-app ...>
    <error-page>
        <location>/general-error.html</location>
    </error-page>
</web-app>

But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

That should cover the most common ones.

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

DOM element to corresponding vue.js component

  • this.$el - points to the root element of the component
  • this.$refs.<ref name> + <div ref="<ref name>" ... - points to nested element

use $el/$refs only after mounted() step of vue lifecycle

<template>
    <div>
        root element
        <div ref="childElement">child element</div>
    </div>
</template>

<script>
    export default {
        mounted() {
            let rootElement = this.$el;
            let childElement = this.$refs.childElement;

            console.log(rootElement);
            console.log(childElement);
        }
    }
</script>

<style scoped>
</style>

enter image description here

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Do not attempt to remove any Apple-supplied system Python which are in /System/Library and /usr/bin, as this may break your whole operating system.


NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.


The complete list is documented here. Basically, all you need to do is the following:

  1. Remove the third-party Python 2.7 framework

    sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
    
  2. Remove the Python 2.7 applications directory

    sudo rm -rf "/Applications/Python 2.7"
    
  3. Remove the symbolic links, in /usr/local/bin, that point to this Python version. See them using

    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' 
    

    and then run the following command to remove all the links:

    cd /usr/local/bin/
    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
    
  4. If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7 to your PATH environment file. Depending on which shell you use, any of the following files may have been modified: ~/.bash_login, ~/.bash_profile, ~/.cshrc, ~/.profile, ~/.tcshrc, and/or ~/.zprofile.

How can I use a reportviewer control in an asp.net mvc 3 razor view?

It is possible to get an SSRS report to appear on an MVC page without using iFrames or an aspx page.

The bulk of the work is explained here:

http://geekswithblogs.net/stun/archive/2010/02/26/executing-reporting-services-web-service-from-asp-net-mvc-using-wcf-add-service-reference.aspx

The link explains how to create a web service and MVC action method that will allow you to call the reporting service and render result of the web service as an Excel file. With a small change to the code in the example you can render it as HTML.

All you need to do then is use a button to call a javascript function that makes an AJAX call to your MVC action which returns the HTML of the report. When the AJAX call returns with the HTML just replace a div with this HTML.

We use AngularJS so my example below is in that format, but it could be any javascript function

$scope.getReport = function()
{
    $http({
        method: "POST",
        url: "Report/ExportReport",
        data: 
                [
                    { Name: 'DateFrom', Value: $scope.dateFrom },
                    { Name: 'DateTo', Value: $scope.dateTo },
                    { Name: 'LocationsCSV', Value: $scope.locationCSV }
                ]

    })
    .success(function (serverData)
    {
        $("#ReportDiv").html(serverData);
    });

};

And the Action Method - mainly taken from the above link...

    [System.Web.Mvc.HttpPost]
    public FileContentResult ExportReport([FromBody]List<ReportParameterModel> parameters)
    {
         byte[] output;
         string extension, mimeType, encoding;
         string reportName = "/Reports/DummyReport";
         ReportService.Warning[] warnings;
         string[] ids;

     ReportExporter.Export(
            "ReportExecutionServiceSoap" 
            new NetworkCredential("username", "password", "domain"),
            reportName,
            parameters.ToArray(),
            ExportFormat.HTML4,
            out output,
            out extension,
            out mimeType,
            out encoding,
            out warnings,
            out ids
        );

        //-------------------------------------------------------------
        // Set HTTP Response Header to show download dialog popup
        //-------------------------------------------------------------
        Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
        return new FileContentResult(output, mimeType);
    }

So the result is that you get to pass parameters to an SSRS reporting server which returns a report which you render as HTML. Everything appears on the one page. This is the best solution I could find

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

What exactly is a Maven Snapshot and why do we need it?

A snapshot version in Maven is one that has not been released.

The idea is that before a 1.0 release (or any other release) is done, there exists a 1.0-SNAPSHOT. That version is what might become 1.0. It's basically "1.0 under development". This might be close to a real 1.0 release, or pretty far (right after the 0.9 release, for example).

The difference between a "real" version and a snapshot version is that snapshots might get updates. That means that downloading 1.0-SNAPSHOT today might give a different file than downloading it yesterday or tomorrow.

Usually, snapshot dependencies should only exist during development and no released version (i.e. no non-snapshot) should have a dependency on a snapshot version.

Android Camera Preview Stretched

@Hesam 's answer is correct, CameraPreview will work in all portrait devices, but if the device is in landscape mode or in multi-window mode, this code is working perfect, just replace onMeasure()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    int rotation = ((Activity) mContext).getWindowManager().getDefaultDisplay().getRotation();
    if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {//portrait
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, height, width);
    } else
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);//landscape

    if (mPreviewSize == null) return;
    float ratio;
    if (mPreviewSize.height >= mPreviewSize.width) {
        ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
    } else ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ((Activity) mContext).isInMultiWindowMode()) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ||
                !(Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            setMeasuredDimension(width, (int) (width / ratio));
        } else {
            setMeasuredDimension((int) (height / ratio), height);
        }
    } else {
        if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            Log.e("---", "onMeasure: " + height + " - " + width * ratio);
            //2264 - 2400.0 pix c -- yes
            //2240 - 2560.0 samsung -- yes
            //1582 - 1440.0 pix 2 -- no
            //1864 - 2048.0 sam tab -- yes
            //848 - 789.4737 iball -- no
            //1640 - 1600.0 nexus 7 -- no
            //1093 - 1066.6667 lenovo -- no
            //if width * ratio is > height, need to minus toolbar height
           if ((width * ratio) < height)
                setMeasuredDimension(width, (int) (width * ratio));
            else
                setMeasuredDimension(width, (int) (width * ratio) - toolbarHeight);
        } else {
            setMeasuredDimension((int) (height * ratio), height);
        }
    }
    requestLayout();
}

comma separated string of selected values in mysql

First to set group_concat_max_len, otherwise it will not give you all the result:

SET GLOBAL  group_concat_max_len = 999999;
SELECT GROUP_CONCAT(id)  FROM table_level where parent_id=4 group by parent_id;

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Objective-C : BOOL vs bool

The Objective-C type you should use is BOOL. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL. (It's defined in the Apple-Frameworks.

Adding an onclick function to go to url in JavaScript?

try

location = url;

_x000D_
_x000D_
function url() {_x000D_
    location = 'https://example.com';_x000D_
}
_x000D_
<input type="button" value="Inline" _x000D_
onclick="location='https://example.com'" />_x000D_
_x000D_
<input type="button" value="URL()" _x000D_
onclick="url()" />
_x000D_
_x000D_
_x000D_

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

How to convert milliseconds into a readable date?

I just tested this and it works fine

var d = new Date(1441121836000);

The data object has a constructor which takes milliseconds as an argument.

How to change a TextView's style at runtime

See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html

To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

Python - Count elements in list

Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

What does the keyword Set actually do in VBA?

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

How to change MenuItem icon in ActionBar programmatically

Its Working

      MenuItem tourchmeMenuItem; // Declare Global .......

 public boolean onCreateOptionsMenu(Menu menu) 
 {
        getMenuInflater().inflate(R.menu.search, menu);
        menu.findItem(R.id.action_search).setVisible(false);
        tourchmeMenuItem = menu.findItem(R.id.done);
        return true;
 }

    public boolean onOptionsItemSelected(MenuItem item) {

    case R.id.done:
                       if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(false);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32));
                            }
                        }else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(true);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32));
                            }
                        }
                        break;

}

How do you get the current page number of a ViewPager for Android?

For this problem Onpagechange listener is the best one But it will also have one small mistake that is it will not detect the starting time time of 0th position Once you will change the page it will starts to detect the Page selected position...For this problem I fount the easiest solution

1.You have to maintain the selected position value then use it....
2. Case 1: At the starting of the position is always Zero....
Case 2: Suppose if you set the current item means you will set that value into maintain position
3.Then do your action with the use of that maintain in your activity...

Public int maintain=0;
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
             //Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected( int i) {
          // here you will get the position of selected page
            maintain = i;


        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });


updateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
            data.set(maintain, "Replaced "+maintain);         
            myViewPager.getAdapter().notifyDataSetChanged();
        }
    });

How do I perform a Perl substitution on a string while keeping the original?

This is the idiom I've always used to get a modified copy of a string without changing the original:

(my $newstring = $oldstring) =~ s/foo/bar/g;

In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier:

my $newstring = $oldstring =~ s/foo/bar/gr; 

NOTE:
The above solutions work without g too. They also work with any other modifiers.

SEE ALSO:
perldoc perlrequick: Perl regular expressions quick start

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Random shuffling of an array

import java.util.ArrayList;
import java.util.Random;
public class shuffle {
    public static void main(String[] args) {
        int a[] =  {1,2,3,4,5,6,7,8,9};
         ArrayList b = new ArrayList();
       int i=0,q=0;
       Random rand = new Random();

       while(a.length!=b.size())
       {
           int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
//           if(a[l] !=0)
//           {
//                b.add(a[l]);
//               a[l]=0;
//               
//           }
//           
// this works for every no. 
                if(!(b.contains(a[l])))
                {
                    b.add(a[l]);
                }



       }

//        for (int j = 0; j <b.size(); j++) {
//            System.out.println(b.get(j));
//            
//        }
System.out.println(b);
    }

}

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

Error: free(): invalid next size (fast):

I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.

A simple:

    int* a;
    class foo{ 
    foo(){
       for(i=0;i<n;i++)
           a=new int[i];
     }

Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.

How to get min, seconds and milliseconds from datetime.now() in python?

Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.

from datetime import datetime

Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]

If you need the values as a number just cast them as an int e.g

Hour = int(str(datetime.now())[11:13])

jQuery - Check if DOM element already exists

Also think about using

$(document).ready(function() {});

Don't know why no one here came up with this yet (kinda sad). When do you execute your code??? Right at the start? Then you might want to use upper mentioned ready() function so your code is being executed after the whole page (with all it's dom elements) has been loaded and not before! Of course this is useless if you run some code that adds dom elements after page load! Then you simply want to wait for those functions and execute your code afterwards...

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

How to get root access on Android emulator?

I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:

On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]

Inside the shell, run these commands:

mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su

Then, install SuperSU and install SU binary. This will replace the SU binary we just created. (Optional) Remove SuperSU and install Superuser by CWM. Install the su binary again. Now, root works!

Filter rows which contain a certain string

edit included the newer across() syntax

Here's another tidyverse solution, using filter(across()) or previously filter_at. The advantage is that you can easily extend to more than one column.

Below also a solution with filter_all in order to find the string in any column, using diamonds as example, looking for the string "V"

library(tidyverse)

String in only one column

# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>% 
  rownames_to_column("type") %>% 
  filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
  head()
#>                type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1        Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 2    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> 3 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#> 4           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> 5        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#> 6         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

The now superseded syntax for the same would be:

mtcars %>% 
  rownames_to_column("type") %>% 
  filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.))) 

String in all columns:

# remove all rows where any column contains 'V'
diamonds %>%
  filter(across(everything(), ~ !grepl('V', .))) %>%
  head
#> # A tibble: 6 x 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

The now superseded syntax for the same would be:

diamonds %>% 
  filter_all(all_vars(!grepl('V', .))) %>%
  head

I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:

    #get all rows where any column contains 'V'
    diamonds %>%
    filter_all(any_vars(grepl('V',.))) %>%
      head
    #> # A tibble: 6 x 10
    #>   carat cut       color clarity depth table price     x     y     z
    #>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
    #> 1 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
    #> 2 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
    #> 3 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
    #> 4 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
    #> 5 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
    #> 6 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:

diamonds %>%
   filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

How to load my app from Eclipse to my Android phone instead of AVD

First you need to set your device to debugging mode. On Android 4.X that means as described in another answer in another question:

Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping “System settings”

Now scroll to the bottom and tap “About phone” or “About tablet”.

At the “About” screen, scroll to the bottom and tap on “Build number” seven times. [Note this is no joke]

Make sure you tap seven times. If you see a “Not need, you are already a developer!” message pop up, then you know you have done it correctly.

Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.

The next step is to connect your device to your computer via the USB cable.

The next step is to install a USB driver for it. On the official website you find a list with sources for drivers for phones from various different companies.

Eclipse now should give you the phone as a choice when you click on Run and it presents you possible device to launch.

In some case Eclpise will tell you Target Unknown which prevents you from using the device. If that's the case you might have to restart the phone. You might also have to check and recheckUSB debugging, till the phone asks you to allow your particular computer to do usb debugging.

Java error: Only a type can be imported. XYZ resolves to a package

I had the same error message and my way to deal with it is as follows:

  1. First go check the file directory where your Tomcat is publishing your web application, e.g. D:\Java\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\myDatatable\WEB-INF\classes, in which we normally put our classes. If this is not the place where you put your classes, then you have to find out where by default it is by right click your web application root name-->Build Path-->Configure Build Bath...-->Then check the "Source" Tab and find out the field value of "Default output folder". This shall be the place where Tomcat put your classes.
  2. You would see that XYZ class is not yet built. In order to build it, you could go to Menu "Project"-->"Clean..."-->Select your web application to clean.
  3. After it's completed, try restart your tomcat server and go check the file directory again. Your class should be there. At least it works for me. Hope it helps.

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had this error on AWS Lightsail, used the top answer above

from

listen [::]:80;

to

listen [::]:80 ipv6only=on default_server;

and then click on "reboot" button inside my AWS account, I have main server Apache and Nginx as proxy.

URL to load resources from the classpath in Java

(Similar to Azder's answer, but a slightly different tact.)

I don't believe there is a predefined protocol handler for content from the classpath. (The so-called classpath: protocol).

However, Java does allow you to add your own protocols. This is done through providing concrete implementations java.net.URLStreamHandler and java.net.URLConnection.

This article describes how a custom stream handler can be implemented: http://java.sun.com/developer/onlineTraining/protocolhandlers/.

How to find sitemap.xml path on websites?

According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

  • Informing each search engine of the location through their provided interface
  • Adding url to the robots.txt file
  • Submiting url to search engines through http

So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

Drop all tables whose names begin with a certain string

On Oracle XE this works:

SELECT 'DROP TABLE "' || TABLE_NAME || '";'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Or if you want to remove the constraints and free up space as well, use this:

SELECT 'DROP TABLE "' || TABLE_NAME || '" cascade constraints PURGE;'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Which will generate a bunch of DROP TABLE cascade constraints PURGE statements...

For VIEWS use this:

SELECT 'DROP VIEW "' || VIEW_NAME || '";'
FROM USER_VIEWS
WHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'

javascript: pause setTimeout();

If you have several divs to hide, you could use an setInterval and a number of cycles to do like in:

<div id="div1">1</div><div id="div2">2</div>
<div id="div3">3</div><div id="div4">4</div>
<script>
    function hideDiv(elm){
        var interval,
            unit = 1000,
            cycle = 5,
            hide = function(){
                interval = setInterval(function(){
                    if(--cycle === 0){
                        elm.style.display = 'none';
                        clearInterval(interval);
                    }
                    elm.setAttribute('data-cycle', cycle);
                    elm.innerHTML += '*';
                }, unit);
            };
        elm.onmouseover = function(){
            clearInterval(interval);
        };
        elm.onmouseout = function(){
            hide();
        };
        hide();
    }
    function hideDivs(ids){
        var id;
        while(id = ids.pop()){
            hideDiv(document.getElementById(id));
        }
    }
    hideDivs(['div1','div2','div3','div4']);
</script>

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

Is there a jQuery unfocus method?

$('#textarea').blur()

Documentation at: http://api.jquery.com/blur/

How to save to local storage using Flutter?

If you need to store just simple values like API token or login data (not passwords!), here is what I used:

import 'package:shared_preferences/shared_preferences.dart';

asyncFunc() async { // Async func to handle Futures easier; or use Future.then
  SharedPreferences prefs = await SharedPreferences.getInstance();
}
...

// Set
prefs.setString('apiToken', token);

// Get
String token = prefs.getString('apiToken');

// Remove
prefs.remove('apiToken');

Don't forget to add shared_preferences dependency in your pubspec.yaml (preserve spacing format):

dependencies:

  shared_preferences: any

Easiest way to detect Internet connection on iOS?

Checking the Internet connection availability in (iOS) Xcode 8.2 , Swift 3.0

This is simple method for checking the network availability. I managed to translate it to Swift 2.0 and here the final code. The existing Apple Reachability class and other third party libraries seemed to be too complicated to translate to Swift.

This works for both 3G and WiFi connections.

Don’t forget to add “SystemConfiguration.framework” to your project builder.

//Create new swift class file Reachability in your project.

import SystemConfiguration

public class Reachability {
class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability! , &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
   }
}

// Check network connectivity from anywhere in project by using this code.

if Reachability.isConnectedToNetwork() == true {
     print("Internet connection OK")
} else {
 print("Internet connection FAILED")
}

Google Maps: How to create a custom InfoWindow?

Styling the infowindow is fairly straightforward with vanilla javascript. I used some of the info from this thread when writing this. I also took into account the possible problems with earlier versions of ie (although I have not tested it with them).

var infowindow = new google.maps.InfoWindow({
  content: '<div id="gm_content">'+contentString+'</div>'
});

google.maps.event.addListener(infowindow,'domready',function(){
  var el = document.getElementById('gm_content').parentNode.parentNode.parentNode;
  el.firstChild.setAttribute('class','closeInfoWindow');
  el.firstChild.setAttribute('title','Close Info Window');
  el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
  el.setAttribute('class','infoWindowContainer');
  for(var i=0; i<11; i++){
    el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
    el.style.display = 'none';
  }
});

The code creates the infowindow as usual (no need for plugins, custom overlays or huge code), using a div with an id to hold the content. This gives a hook in the system that we can use to get the correct elements to manipulate with a simple external stylesheet.

There are a couple of extra pieces (that are not strictly needed) which handle things like giving a hook into the div with the close info window image in it.

The final loop hides all the pieces of the pointer arrow. I needed this myself as I wanted to have transparency on the infowindow and the arrow got in the way. Of course, with the hook, changing the code to replace the arrow image with a png of your choice should be fairly simple too.

If you want to change it to jquery (no idea why you would) then that should be fairly simple.

I'm not usually a javascript developer so any thoughts, comments, criticisms welcome :)

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

Get MD5 hash of big files in Python

u can't get it's md5 without read full content. but u can use update function to read the files content block by block.
m.update(a); m.update(b) is equivalent to m.update(a+b)

Servlet for serving static content

To serve all requests from a Spring app as well as /favicon.ico and the JSP files from /WEB-INF/jsp/* that Spring's AbstractUrlBasedView will request you can just remap the jsp servlet and default servlet:

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>/WEB-INF/jsp/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/favicon.ico</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

We can't rely on the *.jsp url-pattern on the standard mapping for the jsp servlet because the path pattern '/*' is matched before any extension mapping is checked. Mapping the jsp servlet to a deeper folder means it's matched first. Matching '/favicon.ico' exactly happens before path pattern matching. Deeper path matches will work, or exact matches, but no extension matches can make it past the '/*' path match. Mapping '/' to default servlet doesn't appear to work. You'd think the exact '/' would beat the '/*' path pattern on springapp.

The above filter solution doesn't work for forwarded/included JSP requests from the application. To make it work I had to apply the filter to springapp directly, at which point the url-pattern matching was useless as all requests that go to the application also go to its filters. So I added pattern matching to the filter and then learned about the 'jsp' servlet and saw that it doesn't remove the path prefix like the default servlet does. That solved my problem, which was not exactly the same but common enough.

Regular expression to search multiple strings (Textpad)

I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.

CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"

Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1

Tamper 2nd plugin: explode setting: explode by |

In this case you don't need any additinal fields mappings and can use 1 field in CSV

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.

value.ToUniversalTime().ToString("O");

How can you float: right in React Native?

you can use following these component to float right

alignItems aligns children in the cross direction. For example, if children are flowing vertically, alignItems controls how they align horizontally.

alignItems: 'flex-end'

justifyContent aligns children in the main direction. For example, if children are flowing vertically, justifyContent controls how they align vertically.

justifyContent: 'flex-end'

alignSelf controls how a child aligns in the cross direction,

alignSelf : 'flex-end'

Variably modified array at file scope

Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.

Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.

Join two sql queries

Here's what worked for me:

select visits, activations, simulations, simulations/activations
   as sims_per_visit, activations/visits*100
   as adoption_rate, simulations/activations*100
   as completion_rate, duration/60
   as minutes, m1 as month, Wk1 as week, Yr1 as year 

from
(
    (select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
    as m1 from sessions group by week(stamp), year(stamp)) as t3

    join

    (select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
    month(stamp) as m2 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t4

    join

    (select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
    month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
    year(stamp)) as t5

    join

    (select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
    month(stamp) as m4 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4

I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.

Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.

String concatenation in Ruby

Since this is a path I'd probably use array and join:

source = [ROOT_DIR, project, 'App.config'] * '/'