Programs & Examples On #Reportviewer

The Microsoft ReportViewer control enables web and client applications that run on the .NET Framework to display reports designed using SQL Server Reporting Services (SSRS).

Microsoft.ReportViewer.Common Version=12.0.0.0

In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved

Here is the screenshot for installing data tools

Missing Microsoft RDLC Report Designer in Visual Studio

If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.

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

This is a simple task. You can follow the following steps.

  1. Create a folder in your solution and name it Reports.
  2. Add an ASP.Net web form and name it ReportView.aspx
  3. Create a Class ReportData and add it to the Reports folder. Add the following code to the Class.

    public class ReportData  
    {  
        public ReportData()  
        {  
            this.ReportParameters = new List<Parameter>();  
            this.DataParameters = new List<Parameter>();  
        }
    
        public bool IsLocal { get; set; }
        public string ReportName { get; set; }
        public List<Parameter> ReportParameters { get; set; }
        public List<Parameter> DataParameters { get; set; }
    }
    
    public class Parameter  
    {  
        public string ParameterName { get; set; }  
        public string Value { get; set; }  
    }
    
  4. Add another Class and name it ReportBasePage.cs. Add the following code in this Class.

    public class ReportBasePage : System.Web.UI.Page
    {
        protected ReportData ReportDataObj { get; set; }
    
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (HttpContext.Current != null)
                if (HttpContext.Current.Session["ReportData"] != null)
                {
                    ReportDataObj = HttpContext.Current.Session["ReportData"] as ReportData;
                    return;
                }
            ReportDataObj = new ReportData();
            CaptureRouteData(Page.Request);
        }
    
    
        private void CaptureRouteData(HttpRequest request)
        {
            var mode = (request.QueryString["rptmode"] + "").Trim();
            ReportDataObj.IsLocal = mode == "local" ? true : false;
            ReportDataObj.ReportName = request.QueryString["reportname"] + "";
            string dquerystr = request.QueryString["parameters"] + "";
            if (!String.IsNullOrEmpty(dquerystr.Trim()))
            {
                var param1 = dquerystr.Split(',');
                foreach (string pm in param1)
                {
                    var rp = new Parameter();
                    var kd = pm.Split('=');
                    if (kd[0].Substring(0, 2) == "rp")
                    {
                        rp.ParameterName = kd[0].Replace("rp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.ReportParameters.Add(rp);
                    }
                    else if (kd[0].Substring(0, 2) == "dp")
                    {
                        rp.ParameterName = kd[0].Replace("dp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.DataParameters.Add(rp);
                    }
                }
            }
        }
    }
    
  5. Add ScriptManager to the ReportView.aspx page. Now add a Report Viewer to the page. In report viewer set the property AsyncRendering="false". The code is given below.

        <rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
            Width="1271px" Height="1000px" >
        </rsweb:ReportViewer>
    
  6. Add two NameSpace in ReportView.aspx.cs

    using Microsoft.Reporting.WebForms;
    using System.IO;
    
  7. Change the System.Web.UI.Page to ReportBasePage. Just replace your code using the following.

    public partial class ReportView : ReportBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RenderReportModels(this.ReportDataObj);
            }
        }
    
        private void RenderReportModels(ReportData reportData)
        {
            // This is the Data Access Layer from which a method is called to fill data to the list.
            RASolarERPData dal = new RASolarERPData();
            List<ClosingInventoryValuation> objClosingInventory = new List<ClosingInventoryValuation>();
    
            // Reset report properties.
            ReportViewerRSFReports.Height = Unit.Parse("100%");
            ReportViewerRSFReports.Width = Unit.Parse("100%");
            ReportViewerRSFReports.CssClass = "table";
    
            // Clear out any previous datasources.
            this.ReportViewerRSFReports.LocalReport.DataSources.Clear();
    
            // Set report mode for local processing.
            ReportViewerRSFReports.ProcessingMode = ProcessingMode.Local;
    
            // Validate report source.
            var rptPath = Server.MapPath(@"./Report/" + reportData.ReportName +".rdlc");
    
            //@"E:\RSFERP_SourceCode\RASolarERP\RASolarERP\Reports\Report\" + reportData.ReportName + ".rdlc";
            //Server.MapPath(@"./Report/ClosingInventory.rdlc");
    
            if (!File.Exists(rptPath))
                return;
    
            // Set report path.
            this.ReportViewerRSFReports.LocalReport.ReportPath = rptPath;
    
            // Set report parameters.
            var rpPms = ReportViewerRSFReports.LocalReport.GetParameters();
            foreach (var rpm in rpPms)
            {
                var p = reportData.ReportParameters.SingleOrDefault(o => o.ParameterName.ToLower() == rpm.Name.ToLower());
                if (p != null)
                {
                    ReportParameter rp = new ReportParameter(rpm.Name, p.Value);
                    ReportViewerRSFReports.LocalReport.SetParameters(rp);
                }
            }
    
            //Set data paramater for report SP execution
            objClosingInventory = dal.ClosingInventoryReport(this.ReportDataObj.DataParameters[0].Value);
    
            // Load the dataSource.
            var dsmems = ReportViewerRSFReports.LocalReport.GetDataSourceNames();
            ReportViewerRSFReports.LocalReport.DataSources.Add(new ReportDataSource(dsmems[0], objClosingInventory));
    
            // Refresh the ReportViewer.
            ReportViewerRSFReports.LocalReport.Refresh();
        }
    }
    
  8. Add a Folder to the Reports Folder and name it Report. Now add a RDLC report to the Reports/Report folder and name it ClosingInventory.rdlc.

  9. Now add a Controller and name it ReportController. In the controller add the following action method.

    public ActionResult ReportViewer()
        {                
            ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
    
            return View();
        }
    
  10. Add a view page click on the ReportViewer Controller. Name the view page ReportViewer.cshtml. Add the following code to the view page.

    @using (Html.BeginForm("Login"))
     { 
           @Html.DropDownList("ddlYearMonthFormat", new SelectList(ViewBag.YearMonthFormat, "YearMonthValue",
     "YearMonthName"), new { @class = "DropDown" })
    
    Stock In Transit: @Html.TextBox("txtStockInTransit", "", new { @class = "LogInTextBox" })
    
    <input type="submit" onclick="return ReportValidationCheck();" name="ShowReport"
                     value="Show Report" />
    
    }
    
  11. Add an Iframe. Set the property of the Iframe as follows

    frameborder="0"  width="1000"; height="1000"; style="overflow:hidden;"
    scrolling="no"
    
  12. Add Following JavaScript to the viewer.

    function ReportValidationCheck() {
    
        var url = $('#hdUrl').val();
        var yearmonth = $('#ddlYearMonthFormat').val();      
        var stockInTransit = $('#txtStockInTransit').val()
    
        if (stockInTransit == "") {
            stockInTransit = 0;
        }
    
        if (yearmonth == "0") {
            alert("Please Select Month Correctly.");
        }
        else {
    
            //url = url + "dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            url = "../Reports/ReportView.aspx?rptmode=local&reportname=ClosingInventory&parameters=dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            var myframe = document.getElementById("ifrmReportViewer");
            if (myframe !== null) {
                if (myframe.src) {
                    myframe.src = url;
                }
                else if (myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
                    myframe.contentWindow.location = url;
                }
                else { myframe.setAttribute('src', url); }
            }
        }
    
        return false;
    }
    
  13. Web.config file add the following key to the appSettings section

    add key="UnobtrusiveJavaScriptEnabled" value="true"
    
  14. In system.web handlers Section add the following key

    add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    
  15. Change your data source to your own. This solution is very simple and I think every one will enjoy it.

Creating a PDF from a RDLC Report in the Background

The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:

protected void Button1_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;
    string HIJRA_TODAY = "01/10/1435";
    ReportParameter[] param = new ReportParameter[3];
    param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
    param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
    param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);

    byte[] bytes = ReportViewer1.LocalReport.Render(
        "PDF", 
        null, 
        out mimeType, 
        out encoding, 
        out extension, 
        out streamIds, 
        out warnings);

    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader(
        "content-disposition", 
        "attachment; filename= filename" + "." + extension);
    Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    Response.Flush(); // send it to the client to download  
    Response.End();
}    

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

FYI - none of the above worked for me in 2012 SP1...simple solution was to embed credentials in the shared data source and then tell Safari to trust the SSRS server site. Then it worked great! Took days chasing down supposed solutions like above only to find out integrated security won't work reliably on Safari - you have to mess with the keychain on the mac and then still wouldn't work reliably.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

This link gave me a clue that I didn't install a required update (my problemed concerned version nr, v11.0.0.0)

ReportViewer 2012 Update 'Gotcha' to be aware of

I installed the update SQLServer2008R2SP2

I downloaded ReportViewer.msi, which required to have installed Microsoft® System CLR Types for Microsoft® SQL Server® 2012 (look halfway down the page for installer)

In the GAC was now available WebForms v11.0.0.0 (C:\Windows\assembly\Microsoft.ReportViewer.WebForms v11.0.0.0 as well as Microsoft.ReportViewer.Common v11.0.0.0)

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

When is the init() function run?

Something to add to this (which I would've added as a comment but the time of writing this post I'd not yet enough reputation)

Having multiple inits in the same package I've not yet found any guaranteed way to know what order in which they will be run. For example I have:

package config
    - config.go
    - router.go

Both config.go and router.go contain init() functions, but when running router.go's function ran first (which caused my app to panic).

If you're in a situation where you have multiple files, each with its own init() function be very aware that you aren't guaranteed to get one before the other. It is better to use a variable assignment as OneToOne shows in his example. Best part is: This variable declaration will happen before ALL init() functions in the package.

For example

config.go:

var ConfigSuccess = configureApplication()

func init() {
    doSomething()
}

func configureApplication() bool {
    l4g.Info("Configuring application...")
    if valid := loadCommandLineFlags(); !valid {
        l4g.Critical("Failed to load Command Line Flags")
        return false
    }
    return true
}

router.go:

func init() {
    var (
        rwd string
        tmp string
        ok  bool
    )
    if metapath, ok := Config["fs"]["metapath"].(string); ok {
        var err error
        Conn, err = services.NewConnection(metapath + "/metadata.db")
        if err != nil {
            panic(err)
        }
    }
}

regardless of whether var ConfigSuccess = configureApplication() exists in router.go or config.go, it will be run before EITHER init() is run.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

Test for multiple cases in a switch, like an OR (||)

You have to switch it!

switch (true) {
    case ( (pageid === "listing-page") || (pageid === ("home-page") ):
        alert("hello");
        break;
    case (pageid === "details-page"):
        alert("goodbye");
        break;
}

What is the equivalent of Java's final in C#?

It depends on the context.

SQL select only rows with max value on a column

If you have many fields in select statement and you want latest value for all of those fields through optimized code:

select * from
(select * from table_name
order by id,rev desc) temp
group by id 

What does "Git push non-fast-forward updates were rejected" mean?

In my case for exact same error, I was also not the only developer.

So I went to commit & push my changes at same time, seen at bottom of the Commit dialog popup:

Checked option for: Push changes immediately to origin

...but I made the huge mistake of forgetting to hit the Fetch button to see if I have latest, which I did not.

The commit successfully executed, however not the push, but instead gives the same mentioned error; ...even though other developers didn't alter same files as me, I cannot pull latest as same error is presented.

The GUI Solution

Most of the time I prefer sticking with Sourcetree's GUI (Graphical User Interface). This solution might not be ideal, however this is what got things going again for me without worrying that I may lose my changes or compromise more recent updates from other developers.

STEP 1

Right-click on the commit right before yours to undo your locally committed changes and select Reset current branch to this commit like so:

Sourcetree window with right-clicked commit and selecting: Reset current branch to this commit

STEP 2

Once all the loading spinners disappear and Sourcetree is done loading the previous commit, at the top-left of window, click on Pull button...

Sourcetree window with with the Pull button highlighted

...then a dialog popup will appear, and click the OK button at bottom-right:

Sourcetree window dialog popup with the OK button highlighted

STEP 3

After pulling latest, if you do not get any errors, skip to STEP 4 (next step below). Otherwise if you discover any merge conflicts at this point, like I did with my Web.config file:

Sourcetree window showing the error hint: Updates were rejected because the tip of your current branch is behind

...then click on the Stash button at the top, a dialog popup will appear and you will need to write a Descriptive-name-of-your-changes, then click the OK button:

Sourcetree window with Stash button highlighted and dialog popup showing input to name your stash with OK button highlighted

...once Sourcetree is done stashing your altered file(s), repeat actions in STEP 2 (previous step above), and then your local files will have latest changes. Now your changes can be reapplied by opening your STASHES seen at bottom of Sourcetree left column, use the arrow to expand your stashes, then right-click to choose Apply Stash 'Descriptive-name-of-your-changes', and after select OK button in dialog popup that appears:

Sourcetree window with the Stashes section expanded and changes right-clicked with Apply Stash highlighted

Sourcetree dialog popup ask your to confirm if you would like to apply stash you your local copy

IF you have any Merge Conflict(s) right now, go to your preferred text-editor, like Visual Studio Code, and in the affected files select the Accept Incoming Change link, then save:

enter image description here

Then back to Sourcetree, click on the Commit button at top:

enter image description here

then right-click on the conflicted file(s), and under Resolve Conflicts select the Mark Resolved option:

enter image description here

STEP 4

Finally!!! We are now able to commit our file(s), also checkmark the Push changes immediately to origin option before clicking the Commit button:

enter image description here

P.S. while writing this, a commit was submitted by another developer right before I got to commit, so had to pretty much repeat steps.

Replace all elements of Python NumPy Array that are greater than some value

Another way is to use np.place which does in-place replacement and works with multidimentional arrays:

import numpy as np

# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)

# replace 0 with -10
np.place(arr, arr == 0, -10)

Add MIME mapping in web.config for IIS Express

To solve the problem, double-click the "MIME Types" configuration option while having IIS root node selected in the left panel and click "Add..." link in the Actions panel on the right. This will bring up the following dialog. Add .woff file extension and specify "application/x-font-woff" as the corresponding MIME type:

enter image description here

Follow same for woff2 with application/x-font-woff2

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

JavaScript function to add X months to a date

I'm using moment.js library for date-time manipulations. Sample code to add one month:

var startDate = new Date(...);
var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
endDateMoment.add(1, 'months');

Visual Studio 2015 installer hangs during install?

During the installation if you think it has hung (notably during the "Android SDK Setup"), browse to your %temp% directory and order by "Date modified" (descending), there should be a bunch of log files created by the installer.

The one for the "Android SDK Setup" will be named "AndroidSDK_SI.log" (or similar).

Open the file and got to the end of it (Ctrl+End), this should indicate the progress of the current file that is being downloaded.

i.e: "(80%, 349 KiB/s, 99 seconds left)"

Reopening the file, again going to the end, you should see further indication that the download has progressed (or you could just track the modified timestamp of the file [in minutes]).

i.e: "(99%, 351 KiB/s, 1 seconds left)"

Unfortunately, the installer doesn't indicate this progress (it's running in a separate "Java.exe" process, used by the Android SDK).

This seems like a rather long-winded way to check what's happening but does give an indication that the installer hasn't hung and is doing something, albeit very slowly.

How to Join to first row

,Another aproach using common table expression:

with firstOnly as (
    select Orders.OrderNumber, LineItems.Quantity, LineItems.Description, ROW_NUMBER() over (partiton by Orders.OrderID order by Orders.OrderID) lp
    FROM Orders
        join LineItems on Orders.OrderID = LineItems.OrderID
) select *
  from firstOnly
  where lp = 1

or, in the end maybe you would like to show all rows joined?

comma separated version here:

  select *
  from Orders o
    cross apply (
        select CAST((select l.Description + ','
        from LineItems l
        where l.OrderID = s.OrderID
        for xml path('')) as nvarchar(max)) l
    ) lines

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

Forcing label to flow inline with input that they label

If you want they to be paragraph, then use it.

<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>

Both <label> and <input> are paragraph and flow content so you can insert as paragraph elements and as block elements.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

How to build an android library with Android Studio and gradle?

Here is my solution for mac users I think it work for window also:

First go to your Android Studio toolbar

Build > Make Project (while you guys are online let it to download the files) and then

Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then

Run your app that is done it will launch your emulator and configure it then run it!

That is it!!! Happy Coding guys!!!!!!!

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

What is the default root pasword for MySQL 5.7

MySQL server 5.7 was already installed by default on my new Linux Mint 19.

But, what's the MySQL root password? It turns out that:

The default installation uses auth_socket for authentication, in lieu of passwords!

It allows a password-free login, provided that one is logged into the Linux system with the same user name. To login as the MySQL root user, one can use sudo:

sudo mysql --user=root

But how to then change the root password? To illustrate what's going on, I created a new user "me", with full privileges, with:

mysql> CREATE USER 'me'@'localhost' IDENTIFIED BY 'my_new_password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'me'@'localhost' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;

Comparing "me" with "root":

mysql> SELECT user, plugin, HEX(authentication_string)  FROM mysql.user WHERE user = 'me' or user = 'root';
+------+-----------------------+----------------------------------------------------------------------------+
| user | plugin                | HEX(authentication_string)                                                 |
+------+-----------------------+----------------------------------------------------------------------------+
| root | auth_socket           |                                                                            |
| me   | mysql_native_password | 2A393846353030304545453239394634323734333139354241344642413245373537313... |
+------+-----------------------+----------------------------------------------------------------------------+

Because it's using auth_socket, the root password cannot be changed: the SET PASSWORD command fails, and mysql_secure_installation desn't attain anything...

==> To zap this alternate authentication mode and return the MySQL root user to using passwords:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'SOME_NEW_ROOT_PASSWORD';

A good explanation.

More details from the MySQL manual.

Convert tabs to spaces in Notepad++

I just posted a Notepad++ plugin to convert tabs to spaces. Yes, it converts tabs in the middle of a line. Yes, it takes into account other characters within the tabbed field. Check it out.

How to declare 2D array in bash

Another approach is you can represent each row as a string, i.e. mapping the 2D array into an 1D array. Then, all you need to do is unpack and repack the row's string whenever you make an edit:

# Init a 4x5 matrix
a=("00 01 02 03 04" "10 11 12 13 14" "20 21 22 23 24" "30 31 32 33 34")

aset() {
  row=$1
  col=$2
  value=$3
  IFS=' ' read -r -a tmp <<< "${a[$row]}"
  tmp[$col]=$value
  a[$row]="${tmp[@]}"
}

# Set a[2][3] = 9999
aset 2 3 9999

# Show result
for r in "${a[@]}"; do
  echo $r
done

Outputs:

00 01 02 03 04
10 11 12 13 14
20 21 22 9999 24
30 31 32 33 34

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

git: patch does not apply

Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:

git apply --ignore-space-change --ignore-whitespace mychanges.patch

This solved my problem.

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

How can I perform a reverse string search in Excel without using VBA?

Imagine the string could be reversed. Then it is really easy. Instead of working on the string:

"My little cat" (1)

you work with

"tac elttil yM" (2)

With =LEFT(A1;FIND(" ";A1)-1) in A2 you get "My" with (1) and "tac" with (2), which is reversed "cat", the last word in (1).

There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString.

Install the above as described. Then with your string in A1, e.g., "My little cat" and this function in A2:

=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
  LEN(A1);(FIND(" ";ReverseString(A1))-1))))

you'll see "cat" in A2.

The method above assumes that words are separated by blanks. The IF clause is for cells containing single words = no blanks in cell. Note: TRIM and CLEAN the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "). LEFT picks this word and another string reversal reconstitutes the original order of the word (" cat"). The -1 at the end of the FIND statement removes the blank.

The idea is that it is easy to extract the first(!) word in a string with LEFT and FINDing the first blank. However, for the last(!) word the RIGHT function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.

Therefore the whole string is simply reversed. LEFT and FIND work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString statement in the formula does this job.

How to fix libeay32.dll was not found error

I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

I tried the above for a Float64Array and it just did not work.

I ended up realising that really the data needed to be read 'INTO' the view in correct chunks. This means reading 8 bytes at a time from the source Buffer.

Anyway this is what I ended up with...

var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new Float64Array(ab);

var viewIndex = 0;
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8)            {

    view[viewIndex] = buff.readDoubleLE(bufferIndex);
    viewIndex++;
}

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Parsing XML with namespace in Python via 'ElementTree'

To get the namespace in its namespace format, e.g. {myNameSpace}, you can do the following:

root = tree.getroot()
ns = re.match(r'{.*}', root.tag).group(0)

This way, you can use it later on in your code to find nodes, e.g using string interpolation (Python 3).

link = root.find(f"{ns}link")

Counting the number of elements with the values of x in a vector

The most direct way is sum(numbers == x).

numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

Github "Updates were rejected because the remote contains work that you do not have locally."

The supplied answers didn't work for me.

I had an empty repo on GitHub with only the LICENSE file and a single commit locally. What worked was:

$ git fetch
$ git merge --allow-unrelated-histories
Merge made by the 'recursive' strategy.
 LICENSE | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
 create mode 100644 LICENSE

Also before merge you may want to:

$ git branch --set-upstream-to origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Android custom Row Item for ListView

Use a custom Listview.

You can also customize how row looks by having a custom background. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" 
 android:background="#0095FF"> //background color

<ListView android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="0dip"
 android:focusableInTouchMode="false"
 android:listSelector="@android:color/transparent"
 android:layout_weight="2"
 android:headerDividersEnabled="false"
 android:footerDividersEnabled="false"
 android:dividerHeight="8dp" 
 android:divider="#000000" 
 android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>  

MainActivity

Define populateString() in MainActivity

 public class MainActivity extends Activity {

   String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            data_array = populateString(); 
    ListView ll = (ListView) findViewById(R.id.list);
    CustomAdapter cus = new CustomAdapter();
    ll.setAdapter(cus);
}

class CustomAdapter extends BaseAdapter
{
    LayoutInflater mInflater;


    public CustomAdapter()
    {
        mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data_array.length;//listview item count. 
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position; 
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder vh;
        vh= new ViewHolder();

        if(convertView==null )
         {
            convertView=mInflater.inflate(R.layout.row, parent,false);
                    //inflate custom layour
            vh.tv2= (TextView)convertView.findViewById(R.id.textView2);

         }
        else
        {
         convertView.setTag(vh);
        }
               //vh.tv2.setText("Position = "+position);
            vh.tv2.setText(data_array[position]);   
                           //set text of second textview based on position

        return convertView;
    }

 class ViewHolder
 {
    TextView tv1,tv2;
 }

   }  
}

row.xml. Custom layout for each row.

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

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Header" />

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TextView" />

 </LinearLayout>

Inflate a custom layout. Use a view holder for smooth scrolling and performance.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.

enter image description here

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I faced a similar problem, here's how I solved in my case. I verify if the task already is RUNNING or FINISHED because an task can run only once. Below you will see a partial and adapted code from my solution.

public class MyActivity... {
    private MyTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // your code
       task = new MyTask();
       setList();
    }

    private void setList() {
    if (task != null)
        if (task.getStatus().equals(AsyncTask.Status.RUNNING)){
            task.cancel(true);
            task = new MyTask();
            task.execute();         
        } else if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            task = new MyTask();
            task.execute();
        } else 
            task.execute();
    }

    class MyTask extends AsyncTask<Void, Item, Void>{
       List<Item> Itens;

       @Override
       protected void onPreExecute() {

        //your code

        list.setVisibility(View.GONE);
        adapterItem= new MyListAdapter(MyActivity.this, R.layout.item, new ArrayList<Item>());
        list.setAdapter(adapterItem);

        adapterItem.notifyDataSetChanged();
    }

    @Override
    protected Void doInBackground(Void... params) {

        Itens = getItens();
        for (Item item : Itens) {
            publishProgress(item );
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Item ... item ) {           
        adapterItem.add(item[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        //your code
        adapterItem.notifyDataSetChanged();     
        list.setVisibility(View.VISIBLE);
    }

}

}

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Is it possible to change the location of packages for NuGet?

The solution proposed in release notes for 2.1 doesn't work out-of-the-box. They forgot to mention that there is code:

internal string ResolveInstallPath()
{
    if (!string.IsNullOrEmpty(this.OutputDirectory))
    {
        return this.OutputDirectory;
    }
    ISettings settings = this._configSettings;

    ...
}

which prevents it from working. To fix this you need to modify your NuGet.targets file and remove 'OutputDirectory' parameter:

    <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(RequireConsentSwitch)</RestoreCommand>

So now, if you add 'repositoryPath' config somewhere in NuGet.config (see the release notes for a description of valid places to put the config files), it will restore all packages into single location, but... Your .csproj still contains hints to assemblies written as relative paths...

I still don't understand why they went hard way instead of changing PackageManager so it would add hint paths relative to PackagesDir. That's the way I do manually to have different package locations locally (on my desktop) and on build agent.

<Reference Include="Autofac.Configuration, Version=2.6.3.862, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
  <Private>True</Private>
  <HintPath>$(PackagesDir)\Autofac.2.6.3.862\lib\NET40\Autofac.Configuration.dll</HintPath>
</Reference>

How to view user privileges using windows cmd?

For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"

  • Click the Start button, then click Run (Windows XP, Server 2003 or below)

  • Type control userpasswords2 and press Enter on your keyboard.

Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.

You will see a window of user details!

how to display employee names starting with a and then b in sql

select columns
  from table
 where (
         column like 'a%' 
      or column like 'b%' )
 order by column asc

How to add title to subplots in Matplotlib?

In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.

  1. The catch is you can define dynamic axes(ax) as in Line 1 of code and you can set its title inside a loop.
  2. The rows of 2D array is length (len) of axis(ax)
  3. Each row has 2 items i.e. It is list within a list (Point No.2)
  4. set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

Is there a developers api for craigslist.org

Ultimately no. You can query for listings with a search string from an RSS feed such as this:

http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString

As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.

Craigslist Automated Posting API?

Write a note to craigslist asking them to open their API,

Border Height on CSS

For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.

For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.

Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/

An example with list items:

li { 
    list-style: none; 
    padding: 0 10px; 
    display: inline-block;
    border-right: 1px solid #000; 
    line-height: 5px; 
    margin: 20px 0; 
}

<ul>
    <li>cats</li>
    <li>dogs</li>
    <li>birds</li>
    <li>swine!</li>
</ul>

Multi value Dictionary

I don't think you can do that directly. You could create a class containing both your object and double and put an instance of it in the dictionary though.

class Pair
{
    object obj;
    double dbl;
}

Dictionary<int, Pair> = new Dictionary<int, Pair>();

SQL Server, How to set auto increment after creating a table without data loss?

SQL Server: How to set auto-increment on a table with rows in it:

This strategy physically copies the rows around twice which can take a much longer time if the table you are copying is very large.

You could save out your data, drop and rebuild the table with the auto-increment and primary key, then load the data back in.

I'll walk you through with an example:

Step 1, create table foobar (without primary key or auto-increment):

CREATE TABLE foobar(
    id int NOT NULL,
    name nchar(100) NOT NULL,
)

Step 2, insert some rows

insert into foobar values(1, 'one');
insert into foobar values(2, 'two');
insert into foobar values(3, 'three');

Step 3, copy out foobar data into a temp table:

select * into temp_foobar from foobar

Step 4, drop table foobar:

drop table foobar;

Step 5, recreate your table with the primary key and auto-increment properties:

CREATE TABLE foobar(
    id int primary key IDENTITY(1, 1) NOT NULL,
    name nchar(100) NOT NULL,
)

Step 6, insert your data from temp table back into foobar

SET IDENTITY_INSERT temp_foobar ON
INSERT into foobar (id, name) select id, name from temp_foobar;

Step 7, drop your temp table, and check to see if it worked:

drop table temp_foobar;
select * from foobar;

You should get this, and when you inspect the foobar table, the id column is auto-increment of 1 and id is a primary key:

1    one
2    two
3    three

Getting java.net.SocketTimeoutException: Connection timed out in android

I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

AngularJS - Animate ng-view transitions

Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS

How to display line numbers in 'less' (GNU)

If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS doesn't include 'n'.

Turning off line numbers by default (for example, setting LESS=n) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.

I typically run with LESS=RSXin (escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less as needed.

Using JAXB to unmarshal/marshal a List<String>

I have encountered this pattern a few times, I found that the easiest way is to define an inner class with JaxB annotations. (anyways, you'll probably want to define the root tag name)

so your code would look something like this

@GET
@Path("/test2")
public Object test2(){
   MyResourceWrapper wrapper = new MyResourceWrapper();
   wrapper .add("a");
   wrapper .add("b");
   return wrapper ;
}

@XmlRootElement(name="MyResource")
private static class MyResourceWrapper {
       @XmlElement(name="Item")
       List<String> list=new ArrayList<String>();
       MyResourceWrapper (){}

       public void add(String s){ list.add(s);}
 }

if you work with javax.rs (jax-rs) I'd return Response object with the wrapper set as its entity

Maven is not working in Java 8 when Javadoc tags are incomplete

So, save yourself some hours that I didn't and try this if it seems not to work:

 <additionalJOption>-Xdoclint:none</additionalJOption>

The tag is changed for newer versions.

When does a cookie with expiration time 'At end of session' expire?

Just to correct mingos' answer:

If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.

To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.

Example:

Instead of:

document.cookie = "cookie_name=cookie_value; 0; path=/";

Just write:

document.cookie = "cookie_name=cookie_value; path=/";

Find and replace specific text characters across a document with JS

You can use:

str.replace(/text/g, "replaced text");

gcc/g++: "No such file or directory"

Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds:

#include "bar"

or

#include <bar>

The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.

How to tell the compiler where to find it

g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to foo.cc (assume you are compiling from the directory where foo.cc is located):

g++ -Ifrobnicate foo.cc

You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.

Now imagine you have multiple version of bar in different folders, given:


// A/bar
#include<string>
std::string which() { return "A/bar"; }

// B/bar
#include<string>
std::string which() { return "B/bar"; }

// C/bar
#include<string>
std::string which() { return "C/bar"; }

// foo.cc
#include "bar"
#include <iostream>

int main () {
    std::cout << which() << std::endl;
}

The priority with #include "bar" is leftmost:

$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar

As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.

This is true of both forms, include <> and incude "".

Difference between #include <bar> and #include "bar"

Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.

E.g.:

Imagine you have the following files in your project folder:

list
main.cc

with main.cc:

#include "list"
....

For this, your compiler will #include the file list in your project folder, because it currently compiles main.cc and there is that file list in the current folder.

But with main.cc:

#include <list>
....

and then g++ main.cc, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.

This is all a bit simplified, but should give you the basic idea.

Details on <>/""-priorities and -I

According to the gcc-documentation, the priority for include <> is, on a "normal Unix system", as follows:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].

The documentation also states:

You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.

To continue our #include<list> / #include"list" example (same code):

g++ -I. main.cc

and

#include<list>
int main () { std::list<int> l; }

and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

How can you print a variable name in python?

To answer your original question:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

Example:

>>> a = 'some var'
>>> namestr(a, globals())
['a']

As @rbright already pointed out whatever you do there are probably better ways to do it.

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

How to clean node_modules folder of packages that are not in package.json?

I have added few lines inside package.json:

"scripts": {
  ...
  "clean": "rmdir /s /q node_modules",
  "reinstall": "npm run clean && npm install",
  "rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
  ...
}

If you want to clean only you can use this rimraf node_modules or rm -rf node_modules.

It works fine

What is the difference between JOIN and UNION?

Remember that union will merge results (SQL Server to be sure)(feature or bug?)

select 1 as id, 3 as value
union
select 1 as id, 3 as value

id,value

1,3

select * from (select 1 as id, 3 as value) t1 inner join (select 1 as id, 3 as value) t2 on t1.id = t2.id

id,value,id,value

1,3,1,3

Calculate distance between 2 GPS coordinates

This is very easy to do with geography type in SQL Server 2008.

SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm

4326 is SRID for WGS84 elipsoidal Earth model

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

.NET Global exception handler in console application

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

Count occurrences of a char in a string using Bash

awk is very cool, but why not keep it simple?

num=$(echo $var | grep -o "," | wc -l)

How can I get the image url in a Wordpress theme?

You asked of Function but there is an easier way too. When you will upload the image, copy it's URL which is at the top right part of the window (View Screenshot) and paste it in the src='[link you copied]'. Hope this will help if someone is looking for similar problem.

How do shift operators work in Java?

The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.

value= value >> steps  // Right shift, signed data.
value= value << steps  // Left shift, signed data.

Capturing "Delete" Keypress with jQuery

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter.

How to upgrade PowerShell version from 2.0 to 3.0

  1. Install Chocolatey
  2. Run the following commands in CMD

    • choco install powershell

    • choco upgrade powershell

Execute a large SQL script (with GO commands)

Based on Blorgbeard's solution.

foreach (var sqlBatch in commandText.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries))
{
   sqlCommand.CommandText = sqlBatch;
   sqlCommand.ExecuteNonQuery();
}

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Angular 5 ngHide ngShow [hidden] not working

If you want to just toggle visibility and still keep the input in DOM:

<input class="txt" type="password" [(ngModel)]="input_pw" 
 [style.visibility]="isHidden? 'hidden': 'visible'">

The other way around is as per answer by rrd, which is to use HTML hidden attribute. In an HTML element if hidden attribute is set to true browsers are supposed to hide the element from display, but the problem is that this behavior is overridden if the element has an explicit display style mentioned.

_x000D_
_x000D_
.hasDisplay {_x000D_
  display: block;_x000D_
}
_x000D_
<input class="hasDisplay" hidden value="shown" />_x000D_
<input hidden value="not shown">
_x000D_
_x000D_
_x000D_

To overcome this you can opt to use an explicit css for [hidden] that overrides the display;

[hidden] {
  display: none !important;
}

Yet another way is to have a is-hidden class and do:

<input [class.is-hidden]="isHidden"/>

.is-hidden {
      display: none;
 }

If you use display: none the element will be skipped from the static flow and no space will be allocated for the element, if you use visibility: hidden it will be included in the flow and a space will be allocated but it will be blank space.

The important thing is to use one way across an application rather than mixing different ways thereby making the code less maintainable.

If you want to remove it from DOM

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

Android SDK installation doesn't find JDK

Windows 8 running the x64 SDK.

  1. Download the latest JDK from here: Oracle JDK
  2. Once downloaded and extracted go into the JDK file at C:\Program Files\Java\jdk1.7.0_80\bin and double click on the java Application file (it's the only one called just java). This will briefly open the command line.
  3. Begin the process of installing Android Studio again, from scratch. It should automatically detect the SDK now.

For whatever reason Android Studio wouldn't detect it no matter what I put in manually or searched using the browse option.

Pressing back would not work.

Reporting the error would not work.

Adding JAVA_HOME or other suggestions to the C:... would not work.

It was only beginning the installation of Android Studio again after running the java file that it worked.

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

Python - Extracting and Saving Video Frames

To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line 
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

How do you implement a Stack and a Queue in JavaScript?

If you're looking for ES6 OOP implementation of Stack and Queue data-structure with some basic operations (based on linked lists) then it may look like this:

Queue.js

import LinkedList from '../linked-list/LinkedList';

export default class Queue {
  constructor() {
    this.linkedList = new LinkedList();
  }

  isEmpty() {
    return !this.linkedList.tail;
  }

  peek() {
    if (!this.linkedList.head) {
      return null;
    }

    return this.linkedList.head.value;
  }

  enqueue(value) {
    this.linkedList.append(value);
  }

  dequeue() {
    const removedHead = this.linkedList.deleteHead();
    return removedHead ? removedHead.value : null;
  }

  toString(callback) {
    return this.linkedList.toString(callback);
  }
}

Stack.js

import LinkedList from '../linked-list/LinkedList';

export default class Stack {
  constructor() {
    this.linkedList = new LinkedList();
  }

  /**
   * @return {boolean}
   */
  isEmpty() {
    return !this.linkedList.tail;
  }

  /**
   * @return {*}
   */
  peek() {
    if (!this.linkedList.tail) {
      return null;
    }

    return this.linkedList.tail.value;
  }

  /**
   * @param {*} value
   */
  push(value) {
    this.linkedList.append(value);
  }

  /**
   * @return {*}
   */
  pop() {
    const removedTail = this.linkedList.deleteTail();
    return removedTail ? removedTail.value : null;
  }

  /**
   * @return {*[]}
   */
  toArray() {
    return this.linkedList
      .toArray()
      .map(linkedListNode => linkedListNode.value)
      .reverse();
  }

  /**
   * @param {function} [callback]
   * @return {string}
   */
  toString(callback) {
    return this.linkedList.toString(callback);
  }
}

And LinkedList implementation that is used for Stack and Queue in examples above may be found on GitHub here.

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

This is fixed in Android 4.2 and also in the support library's source.[*]

For details of the cause (and work-arounds) refer to the the Google bug report: http://code.google.com/p/android/issues/detail?id=19917

If you're using the support library then you shouldn't have to worry about this bug (for long)[*]. However, if you're using the API directly (i.e. Not using the support library's FragmentManager) and targeting an API below Android 4.2 then you will need to try one of the work-arounds.

[*] At the time of writing the Android SDK Manager is still distributing an old version that exhibits this bug.

Edit I'm going to add some clarification here because I've obviously somehow confused whoever down-voted this answer.

There are several different (but related) circumstances that can cause this exception to be thrown. My answer above is referring to the specific instance discussed in the question i.e. a bug in Android which has subsequently been fixed. If you're getting this exception for another reason it's because you're adding/removing fragments when you shouldn't be (after fragment states have been saved). If you're in such a situation then perhaps "Nested Fragments - IllegalStateException “Can not perform this action after onSaveInstanceState”" can be of use to you.

This could be due to the service endpoint binding not using the HTTP protocol

I think the best way to solve this is to follow the error advice, hence looking for server logs. To enable logs I added

 <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\logs\TracesServ_ce.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

Then you go to c:\logs\TracesServ_ce.svclog open it with microsoft service trace viewer. And see what the problem really is.

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

Unix's 'ls' sort by name

ls from coreutils performs a locale-aware sort by default, and thus may produce surprising results in some cases (for instance, %foo will sort between bar and quux in LANG=en_US). If you want an ASCIIbetical sort, use

LANG=C ls

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

How to split a data frame?

You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.

x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))

gives

$`1`
   num let LET
3    3   c   C
6    6   f   F
10  10   j   J
12  12   l   L
14  14   n   N
15  15   o   O
17  17   q   Q
18  18   r   R
20  20   t   T
21  21   u   U
22  22   v   V
23  23   w   W
26  26   z   Z

$`2`
   num let LET
1    1   a   A
2    2   b   B
4    4   d   D
5    5   e   E
7    7   g   G
8    8   h   H
9    9   i   I
11  11   k   K
13  13   m   M
16  16   p   P
19  19   s   S
24  24   x   X
25  25   y   Y

You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl column in mtcars:

split(mtcars,mtcars$cyl)

powershell is missing the terminator: "

This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:

"c:\users\abc\"

instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.

"c:\users\abc\\"

Select multiple columns in data.table by their numeric indices

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

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

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

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

do { ... } while (0) — what is it good for?

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');

Print JSON parsed object?

I don't know how it was never made officially, but I've added my own json method to console object for easier printing stringified logs:

Observing Objects (non-primitives) in javascript is a bit like quantum mechanics..what you "measure" might not be the real state, which already have changed.

_x000D_
_x000D_
console.json = console.json || function(argument){_x000D_
    for(var arg=0; arg < arguments.length; ++arg)_x000D_
        console.log(  JSON.stringify(arguments[arg], null, 4)  )_x000D_
}_x000D_
_x000D_
// use example_x000D_
console.json(   [1,'a', null, {a:1}], {a:[1,2]}    )
_x000D_
_x000D_
_x000D_

Many times it is needed to view a stringified version of an Object because printing it as-is (raw Object) will print a "live" version of the object which gets mutated as the program progresses, and will not mirror the state of the object at the logged point-of-time, for example:

var foo = {a:1, b:[1,2,3]}

// lets peek under the hood
console.log(foo) 

// program keeps doing things which affect the observed object
foo.a = 2
foo.b = null

How to force garbage collection in Java?

JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.

So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

Sort array of objects by string property value

In ES6/ES2015 or later you can do this way:

objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));

Prior to ES6/ES2015

objs.sort(function(a, b) {
    return a.last_nom.localeCompare(b.last_nom)
});

Check if an array item is set in JS

The most effective way:

if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

char *array and char array[]

It's very similar to

char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};

but gives you read-only memory.

For a discussion of the difference between a char[] and a char *, see comp.lang.c FAQ 1.32.

SQL Inner Join On Null Values

This article has a good discussion on this issue. You can use

SELECT * 
FROM Y
INNER JOIN X ON EXISTS(SELECT X.QID 
                       INTERSECT 
                       SELECT y.QID);

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

Incrementing a date in JavaScript

The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:

var tomorrow = new Date(today.getTime()+1000*60*60*24);

Javascript : natural sort of alphanumerical strings

So you need a natural sort ?

If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.

It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:

What is the difference between concurrent programming and parallel programming?

Concurrency and Parallelism Source

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.

When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.

For example, in a matrix multiplication that has the same number of threads and processors, each thread (and each processor) computes a row of the result.

How To Run PHP From Windows Command Line in WAMPServer

Try using batch file

  1. Open notepad
  2. type php -S localhost:8000
  3. save file as .bat extension, server.bat
  4. now click on server.bat file your server is ready on http://localhost:8000

Dependency

if you got error php not recognize any internal or external command then goto environment variable and edit path to php.exe "C:\wamp\bin\php\php5.4.3"

Creating a select box with a search option

Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps

$.widget is not a function

May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....

ImportError: cannot import name main when running pip --version command in windows7 32 bit

Even though the original question seems to be from 2015, this 'bug' seems to affect users installing pip-10.0.0 as well.

The workaround is not to modify pip, however to change the way pip is called. Instead of calling /usr/bin/pip call pip via Python itself. For example, instead of the below:

pip install <package>

If from Python version 2 (or default Python binary is called python) do :

python -m pip install <package>

or if from Python version 3:

python3 -m pip install <package> 

"Android library projects cannot be launched"?

our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."

right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.

How to set time zone of a java.util.Date?

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

angular ng-repeat in reverse

The orderBy filter performs a stable sorting as of Angular 1.4.5. (See the GitHub pull request https://github.com/angular/angular.js/pull/12408.)

So it is sufficient to use a constant predicate and reverse set to true:

<div ng-repeat="friend in friends | orderBy:0:true">{{friend.name}}</div>

How to change the style of a DatePicker in android?

To change DatePicker colors (calendar mode) at application level define below properties.

<style name="MyAppTheme" parent="Theme.AppCompat.Light">
    <item name="colorAccent">#ff6d00</item>
    <item name="colorControlActivated">#33691e</item>
    <item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
    <item name="colorControlHighlight">#d50000</item>
</style>

See http://www.zoftino.com/android-datepicker-example for other DatePicker custom styles

zoftino DatePicker examples

How to see if an object is an array without using reflection?

You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

Hide HTML element by id

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

Converting from byte to int in java

Primitive data types (such as byte) don't have methods in java, but you can directly do:

int i=rno[0];

ASP.NET strange compilation error

What worked for me... It seems if you install (or a dependent package installs) Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package it makes some web.config transforms that allow you to use C#7.x features in ASP.NET Razor pages. Whilst I found these worked fine on my local machine they didn't work on our server (even when the compiler was in the /bin/ folder).

The solution was to locate the element below and remove completely from web.config

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>

invalid use of non-static data member

In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA doesn't have any specific instance of foo whose a it can be returning. I'm guessing that what you want is something like:

    class bar {
      private:
        foo * const owner;
      public:
        bar(foo & owner) : owner(&owner) { }
        int getA() {return owner->a;}
    };

But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected member a. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

In one reusable piece of code I use the directive <%@include file="reuse.html"%> and in the second I use the standard action <jsp:include page="reuse.html" />.

Let the code in the reusable file be:

<html>
<head>
    <title>reusable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <img src="candle.gif" height="100" width="50"/> <br />
    <p><b>As the candle burns,so do I</b></p>
</body>

After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet of the two JSP files, you will see the difference.

Here is what you will see when you use the directive:

out.write("<html>\r\n");
out.write("    <head>\r\n");
out.write("        <title>reusable</title>\r\n");
out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("    </head>\r\n");
out.write("    <body>\r\n");
out.write("        <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write("        <p><b>As the candle burns,so do I</b></p>\r\n");
out.write("    </body>\r\n");
out.write("</html>\r\n");
 

And this is what you will see for the used standard action in the second JSP file :

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);

So now you know that the include directive inserts the source of reuse.html at translation time, but the action tag inserts the response of reuse.html at runtime.

If you think about it, there is an extra performance hit with every action tag (<jsp:include>). It means you can guarantee you will always have the latest content, but it increases performance cost.

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

A "release" is the final build for a version which does not change.

A "snapshot" is a build which can be replaced by another build which has the same name. It implies that the build could change at any time and is still under active development.

You have different artifacts for different builds based on the same code. E.g. you might have one with debugging and one without. One for Java 5.0 and one for Java 6. Generally its simpler to have one build which does everything you need. ;)

HTML colspan in CSS

There is no colspan in css as far as I know, but there will be column-span for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div and span with table-like display like this.

This would be the HTML:

<div class="table">
  <div class="row">
    <span class="cell red first"></span>
    <span class="cell blue fill"></span>
    <span class="cell green last"></span>
  </div>
</div>
<div class="table">
  <div class="row">
    <span class="cell black"></span>
  </div>
</div>

And this would be the css:

  /* this is to reproduce table-like structure
     for the sake of table-less layout. */
  .table { display:table; table-layout:fixed; width:100px; }
  .row { display:table-row; height:10px; }
  .cell { display:table-cell; }

  /* this is where the colspan tricks works. */
  span { width:100%; }

  /* below is for visual recognition test purposes only. */
  .red { background:red; }
  .blue { background:blue; }
  .green { background:green; }
  .black { background:black; }

  /* this is the benefit of using table display, it is able 
     to set the width of it's child object to fill the rest of 
     the parent width as in table */
  .first { width: 20px; }
  .last { width: 30px; }
  .fill { width: 100%; }

The only reason to use this trick is to gain the benefit of table-layout behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.

But if you don't need to benefit from the table-layout behaviour, then durilai's answer would suit you enough.

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

For Cordova Apps:

We need to place the google-services.json file in app root (I believe; when working with Cordova apps, we are not to get into other folders/files such as Gradle, Java files, platforms, etc; instead only work with them VIA the config.xml and www folder) and refer it in the config.xml like so:

<platform name="android">
    <!-- Add this line -->
    <resource-file src="google-services.json" target="app/google-services.json" />
</platform>

NOTE: Ensure that the Firebase App packagename is same as the id attribute in <widget id="<packagename>" ... > are same.

For ex:

<!-- config.xml of Cordova App -->
<widget id="com.appFactory.torchapp" ...>

<!--google-serivces.json from generated from Firebase console.-->
{
  ...
  packagename: "com.appFactory.torchapp",
  ...
}

Good Luck...

How do I format a date with Dart?

This give you the date like in a social network : ["today","yesterday","dayoftheweek",etc..]

void main() {
      DateTime now = new DateTime(2018,6,26);
      print(date(now));
    }
    
    String date(DateTime tm) {
      DateTime today = new DateTime.now();
      Duration oneDay = new Duration(days: 1);
      Duration twoDay = new Duration(days: 2);
      Duration oneWeek = new Duration(days: 7);
      String month;
      switch (tm.month) {
        case 1:
          month = "january";
          break;
        case 2:
          month = "february";
          break;
        case 3:
          month = "march";
          break;
        case 4:
          month = "april";
          break;
        case 5:
          month = "may";
          break;
        case 6:
          month = "june";
          break;
        case 7:
          month = "july";
          break;
        case 8:
          month = "august";
          break;
        case 9:
          month = "september";
          break;
        case 10:
          month = "october";
          break;
        case 11:
          month = "november";
          break;
        case 12:
          month = "december";
          break;
      }
    
      Duration difference = today.difference(tm);
    
      if (difference.compareTo(oneDay) < 1) {
        return "today";
      } else if (difference.compareTo(twoDay) < 1) {
        return "yesterday";
      } else if (difference.compareTo(oneWeek) < 1) {
        switch (tm.weekday) {
          case 1:
            return "monday";
          case 2:
            return "tuesday";
          case 3:
            return "wednesday";
          case 4:
            return "thursday";
          case 5:
            return "friday";
          case 6:
            return "saturday";
          case 7:
            return "sunday";
        }
      } else if (tm.year == today.year) {
        return '${tm.day} $month';
      } else {
        return '${tm.day} $month ${tm.year}';
      }
    }

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

Can you test google analytics on a localhost address?

I came across this problem recently, and I found it helpful to explore the new documentation by Google on debugging Analytics. It didn't actually care about sending tracking info to Google Analytics, I just wanted to ensure that the events were firing correctly, and the debugging tools gave me the info I needed. YMMV, I realize doesn't exactly answer the question.

Duplicate keys in .NET dictionaries?

This is a tow way Concurrent dictionary I think this will help you:

public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
    private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
    private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();

    public ICollection<T1> Keys
    {
        get
        {
            return _keyValue.Keys;
        }
    }

    public ICollection<T2> Values
    {
        get
        {
            return _valueKey.Keys;
        }
    }

    public int Count
    {
        get
        {
            return _keyValue.Count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public List<T2> this[T1 index]
    {
        get { return _keyValue[index]; }
        set { _keyValue[index] = value; }
    }

    public List<T1> this[T2 index]
    {
        get { return _valueKey[index]; }
        set { _valueKey[index] = value; }
    }

    public void Add(T1 key, T2 value)
    {
        lock (this)
        {
            if (!_keyValue.TryGetValue(key, out List<T2> result))
                _keyValue.TryAdd(key, new List<T2>() { value });
            else if (!result.Contains(value))
                result.Add(value);

            if (!_valueKey.TryGetValue(value, out List<T1> result2))
                _valueKey.TryAdd(value, new List<T1>() { key });
            else if (!result2.Contains(key))
                result2.Add(key);
        }
    }

    public bool TryGetValues(T1 key, out List<T2> value)
    {
        return _keyValue.TryGetValue(key, out value);
    }

    public bool TryGetKeys(T2 value, out List<T1> key)
    {
        return _valueKey.TryGetValue(value, out key);
    }

    public bool ContainsKey(T1 key)
    {
        return _keyValue.ContainsKey(key);
    }

    public bool ContainsValue(T2 value)
    {
        return _valueKey.ContainsKey(value);
    }

    public void Remove(T1 key)
    {
        lock (this)
        {
            if (_keyValue.TryRemove(key, out List<T2> values))
            {
                foreach (var item in values)
                {
                    var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
                }
            }
        }
    }

    public void Remove(T2 value)
    {
        lock (this)
        {
            if (_valueKey.TryRemove(value, out List<T1> keys))
            {
                foreach (var item in keys)
                {
                    var remove2 = _keyValue.TryRemove(item, out List<T2> values);
                }
            }
        }
    }

    public void Clear()
    {
        _keyValue.Clear();
        _valueKey.Clear();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _keyValue.GetEnumerator();
    }
}

examples:

public class TestA
{
    public int MyProperty { get; set; }
}

public class TestB
{
    public int MyProperty { get; set; }
}

            HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();

            var a = new TestA() { MyProperty = 9999 };
            var b = new TestB() { MyProperty = 60 };
            var b2 = new TestB() { MyProperty = 5 };
            hashMapDictionary.Add(a, b);
            hashMapDictionary.Add(a, b2);
            hashMapDictionary.TryGetValues(a, out List<TestB> result);
            foreach (var item in result)
            {
                //do something
            }

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

What svn command would list all the files modified on a branch?

This will list only modified files:

svn status -u | grep M

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just change your line of code to

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

Can I make a <button> not submit a form?

<form onsubmit="return false;">
   ...
</form>

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

Linux command to print directory structure in the form of a tree

Since it was a successful comment, I am adding it as an answer:
with files:

 find . | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/" 

How to set a variable to be "Today's" date in Python/Pandas

Easy solution in Python3+:

import time


todaysdate = time.strftime("%d/%m/%Y")

#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")

JPA EntityManager: Why use persist() over merge()?

Another observation:

merge() will only care about an auto-generated id(tested on IDENTITY and SEQUENCE) when a record with such an id already exists in your table. In that case merge() will try to update the record. If, however, an id is absent or is not matching any existing records, merge() will completely ignore it and ask a db to allocate a new one. This is sometimes a source of a lot of bugs. Do not use merge() to force an id for a new record.

persist() on the other hand will never let you even pass an id to it. It will fail immediately. In my case, it's:

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist

hibernate-jpa javadoc has a hint:

Throws: javax.persistence.EntityExistsException - if the entity already exists. (If the entity already exists, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.)

Set maxlength in Html Textarea

simple way to do maxlength for textarea in html4 is:

<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>

Change the "100" to however many characters you want

Best way to display data via JSON using jQuery

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});

Basic Authentication Using JavaScript

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

Using margin / padding to space <span> from the rest of the <p>

Add this style to your span:

position:relative; 
top: 10px;

Demo: http://jsfiddle.net/BqTUS/3/

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Ruby: kind_of? vs. instance_of? vs. is_a?

I also wouldn't call two many (is_a? and kind_of? are aliases of the same method), but if you want to see more possibilities, turn your attention to #class method:

A = Class.new
B = Class.new A

a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class

HTML5 best practices; section/header/aside/article elements

[explanations in my “main answer”]

line 7. section around the whole website? Or only a div?

Neither. For styling: use the <body>, it’s already there. For sectioning/semantics: as detailed in my example HTML its effect is contrary to usefulness. Extra wrappers to already wrapped content is no improvement, but noise.


line 8. Each section start with a header?

No, it is the author’s choice where to put content typically summarized as “header”. And if that header-content is clearly recognizable without extra marking, it may perfectly stay without <header>. This is also the author’s choice.


line 23. Is this div right? or must this be a section?

The <div> is probably wrong. It depends on the intentions: is it for styling only it could be right. If it’s for semantic purposes it is wrong: it should be an <article> instead as shown in my other answer. <article> is also right if it is for both styling and sectioning combined.

<section> looks wrong here, as there are no similar sections before or after this one, like chapters in a book. (This is the purpose of <section>).


line 24. Split left/right column with a div.

No. Why?


line 25. Right place for the article tag?

Yes, makes sense.


line 26. Is it required to put your h1-tag in the header-tag?

No. A lone <h*> element probably never needs to go in a <header> (but it can if you want to) as it is already clear that it’s the heading of what is about to come. – It would make sense if that <header> also encompassed a tagline (marked with <p>), for example.


line 43. The content is not related to the main article, so I decided this is a section and not an aside.

It is a misunderstanding that an <aside> has to be “tangentially related” to the content around. The point is: use an <aside> if the content is only “tangentially related” or not at all!

Nevertheless, apart from <aside> being a decent choice, <article> might still be better than a <section> as “hot items” and “new items” are not to be read like two chapters in a book. You can perfectly go for one of them and not the other like an alternative sorting of something, not like two parts of a whole.


line 44. H2 without header

Is great.


line 53. section without header

Well, there is no <header>, but the <h2>-heading leaves pretty clear which part in this section is the header.


line 63. Div with all (non-related) news items

<article> or <aside> might be better.


line 64. header with h2

Discussed already.


line 65. Hmm, div or section? Or remove this div and only use the article-tag

Exactly! Remove the <div>.


line 105. Footer :-)

Very reasonable.

How can I declare and use Boolean variables in a shell script?

I found the existing answers confusing.

Personally, I just want to have something which looks and works like C.

This snippet works many times a day in production:

snapshotEvents=true

if ($snapshotEvents)
then
    # Do stuff if true
fi

and to keep everyone happy, I tested:

snapshotEvents=false

if !($snapshotEvents)
then
    # Do stuff if false
fi

Which also worked fine.

The $snapshotEvents evaluates the contents of value of the variable. So you need the $.

You don't really need the parentheses, I just find them helpful.

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

FormsAuthentication.SignOut() does not log the user out

After lots of search finally this worked for me . I hope it helps.

public ActionResult LogOff()
{
    AuthenticationManager.SignOut();
    HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
    return RedirectToAction("Index", "Home");
}

<li class="page-scroll">@Html.ActionLink("Log off", "LogOff", "Account")</li>

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

How to detect a mobile device with JavaScript?

Another possibility is to use mobile-detect.js. Try the demo.

Browser usage:

<script src="mobile-detect.js"></script>
<script>
    var md = new MobileDetect(window.navigator.userAgent);
    // ... see below
</script>

Node.js / Express:

var MobileDetect = require('mobile-detect'),
    md = new MobileDetect(req.headers['user-agent']);
// ... see below

Example:

var md = new MobileDetect(
    'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
    ' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
    ' Version/4.0 Mobile Safari/534.30');

// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding

console.log( md.mobile() );          // 'Sony'
console.log( md.phone() );           // 'Sony'
console.log( md.tablet() );          // null
console.log( md.userAgent() );       // 'Safari'
console.log( md.os() );              // 'AndroidOS'
console.log( md.is('iPhone') );      // false
console.log( md.is('bot') );         // false
console.log( md.version('Webkit') );         // 534.3
console.log( md.versionStr('Build') );       // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
{
  $i: 1;
  @while $i <= $iterations
  {
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    }
    $i: $i + 1;
  }
}
@include fontResize($mqIterations);

Where are shared preferences stored?

Use http://facebook.github.io/stetho/ library to access your app's local storage with chrome inspect tools. You can find sharedPreference file under Local storage -> < your app's package name >

enter image description here

Set custom attribute using JavaScript

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");

But you really should be using data followed with a dash and with its property, like:

<li ... data-icon="base.gif" ...>

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif";

Switch case with conditions

Switch case is every help full instead of if else statement :

     switch ($("[id*=btnSave]").val()) {
        case 'Search':
            saveFlight();
            break;
        case 'Update':
            break;
        case 'Delete':
            break;
        default:
            break;
    }

Generate unique random numbers between 1 and 100

Adding another better version of same code (accepted answer) with JavaScript 1.6 indexOf function. Do not need to loop thru whole array every time you are checking the duplicate.

var arr = []
while(arr.length < 8){
  var randomnumber=Math.ceil(Math.random()*100)
  var found=false;
    if(arr.indexOf(randomnumber) > -1){found=true;}
  if(!found)arr[arr.length]=randomnumber;
}

Older version of Javascript can still use the version at top

PS: Tried suggesting an update to the wiki but it was rejected. I still think it may be useful for others.

Regular expression to match balanced parentheses

Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.

Lua

Use %b() (%b{} / %b[] for curly braces / square brackets):

  • for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end (see demo)

Raku (former Perl6):

Non-overlapping multiple balanced parentheses matches:

my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)

Overlapping multiple balanced parentheses matches:

say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)

See demo.

Python re non-regex solution

See poke's answer for How to get an expression between balanced parentheses.

Java customizable non-regex solution

Here is a customizable solution allowing single character literal delimiters in Java:

public static List<String> getBalancedSubstrings(String s, Character markStart, 
                                 Character markEnd, Boolean includeMarkers) 

{
        List<String> subTreeList = new ArrayList<String>();
        int level = 0;
        int lastOpenDelimiter = -1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == markStart) {
                level++;
                if (level == 1) {
                    lastOpenDelimiter = (includeMarkers ? i : i + 1);
                }
            }
            else if (c == markEnd) {
                if (level == 1) {
                    subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
                }
                if (level > 0) level--;
            }
        }
        return subTreeList;
    }
}

Sample usage:

String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]

pytest cannot import module while python can

Kept everything same and just added a blank test file at the root folder .. Solved it

Here are the findings, this problem really bugged me for a while. My folder structure was

mathapp/
    - server.py  
    - configuration.py 
    - __init__.py 
    - static/ 
       - home.html  
tests/            
    - functional 
       - test_errors.py 
    - unit  
       - test_add.py

and pytest would complain with the ModuleNotFoundError and gives the HINT - make sure your test modules/packages have valid Python names.

I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

Result without the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================

Results with the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

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

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

SQL query question: SELECT ... NOT IN

Sorry if I've missed the point, but wouldn't the following do what you want on it's own?

SELECT distinct idCustomer FROM reservations 
WHERE DATEPART(hour, insertDate) >= 2

Add timestamp column with default NOW() for new rows only

You need to add the column with a default of null, then alter the column to have default now().

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();

How to install gdb (debugger) in Mac OSX El Capitan?

Once you get the macports version of gdb installed you will need to disable SIP in order to make the proper edits to /System/Library/LaunchDaemons/com.apple.taskgated.plist. To disable SIP, you need to restart in recovery mode and execute the following command:

csrutil disable

Then restart. Then you will need to edit the bottom part of com.apple.taskgated.plist like this:

<array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
</array>

Then you will have to restart to have the changes take effect. Then you should reenable SIP. The gdb command for the macports install is actually ggdb. You will need to code sign ggdb following the instructions here:

https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html

The only way I have been able to get the code signing to work is by running ggdb with sudo. Good luck!

The backend version is not supported to design database diagrams or tables

This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.


Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.

jquery, domain, get URL

Similar to the answer before there there is

location.host

The location global has more fun facts about the current url as well. ( protocol, host, port, pathname, search, hash )

Simplest way to profile a PHP script

XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to DBG debugger Its php benchmarking provides timing for functions, methods, modules and even lines.

How can I perform static code analysis in PHP?

See Semantic Designs' CloneDR, a "clone detection" tool that finds copy/paste/edited code.

It will find exact and near miss code fragments, in spite of white space, comments and even variable renamings. A sample detection report for PHP can be found at the website. (I'm the author.)

How do you deploy Angular apps?

Hopefully this may help, and hopefully I'll get to try this during the week.

  1. Create Web app at Azure
  2. Create Angular 2 app in vs code.
  3. Webpack to bundle.js.
  4. Download Azure site published profile xml
  5. Configure Azure-deploy using https://www.npmjs.com/package/azure-deploy with site profile.
  6. Deploy.
  7. Taste the cream.

What is the worst real-world macros/pre-processor abuse you've ever come across?

See this answer re how a dyslexic colleague made life easier for themselves with a common header file full of things like #define fasle false.

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

Javascript get Object property Name

If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys:

theTypeIs = Object.keys(myVar)[0];

HTML 5 video recording and storing a stream

Currently there is no production ready HTML5 only solution for recording video over the web. The current available solutions are as follows:

HTML Media Capture

Works on mobile devices and uses the OS' video capture app to capture video and upload/POST it to a web server. You will get .mov files on iOS (these are unplayable on Android I've tried) and .mp4 and .3gp on Android. At least the codecs will be the same: H.264 for video and AAC for audio in 99% of the devices.

HTML Media Capture

Image courtesy of https://addpipe.com/blog/the-new-video-recording-prompt-for-media-capture-in-ios9/

Flash and a media server on desktop.

Video recording in Flash works like this: audio and video data is captured from the webcam and microphone, it's encoded using Sorenson Spark or H.264 (video) and Nellymoser Asao or Speex (audio) then it's streamed (rtmp) to a media server (Red5, AMS, Wowza) where it is saved in .flv or .f4v files.

The MediaStream Recording proposal

The MediaStream Recording is a proposal by the the Media Capture Task Force (a joint task force between the WebRTC and Device APIs working groups) for a JS API who's purpose is to make basic video recording in the browser very simple.

Not supported by major browsers. When it'll get implemented (if it will) you will most probably end up with different filetypes (at least .ogg and .webm) and audio/video codecs depending on the browser.

Commercial solutions

There are a few saas and software solutions out there that will handle some or all of the above including addpipe.com, HDFVR, Nimbb and Cameratag.

Further reading:

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

Shortest and quickest way to remove all the selection, is by passing empty string in jQuery .val() function :

$("#my_select").val('')

HttpServletRequest - Get query string parameters, no form data

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

What are the Ruby File.open modes and options?

opt is new for ruby 1.9. The various options are documented in IO.new : www.ruby-doc.org/core/IO.html

Android - How to achieve setOnClickListener in Kotlin?

Here is an example on how to use the onClickListener in Kotlin

button1.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                //Your code here
            }})

Set HTML element's style property in javascript

Don't set the style object itself, set the background color property of the style object that is a property of the element.

And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.

And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized

String concatenation: concat() vs "+" operator

How about some simple testing? Used the code below:

long start = System.currentTimeMillis();

String a = "a";

String b = "b";

for (int i = 0; i < 10000000; i++) { //ten million times
     String c = a.concat(b);
}

long end = System.currentTimeMillis();

System.out.println(end - start);
  • The "a + b" version executed in 2500ms.
  • The a.concat(b) executed in 1200ms.

Tested several times. The concat() version execution took half of the time on average.

This result surprised me because the concat() method always creates a new string (it returns a "new String(result)". It's well known that:

String a = new String("a") // more than 20 times slower than String a = "a"

Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation. If you don't believe the statement above, test for your self.

How to get the nth occurrence in a string?

Because recursion is always the answer.

function getPosition(input, search, nth, curr, cnt) {
    curr = curr || 0;
    cnt = cnt || 0;
    var index = input.indexOf(search);
    if (curr === nth) {
        if (~index) {
            return cnt;
        }
        else {
            return -1;
        }
    }
    else {
        if (~index) {
            return getPosition(input.slice(index + search.length),
              search,
              nth,
              ++curr,
              cnt + index + search.length);
        }
        else {
            return -1;
        }
    }
}

Is it possible to make abstract classes in Python?

I find the accepted answer, and all the others strange, since they pass self to an abstract class. An abstract class is not instantiated so can't have a self.

So try this, it works.

from abc import ABCMeta, abstractmethod


class Abstract(metaclass=ABCMeta):
    @staticmethod
    @abstractmethod
    def foo():
        """An abstract method. No need to write pass"""


class Derived(Abstract):
    def foo(self):
        print('Hooray!')


FOO = Derived()
FOO.foo()

Why is there no String.Empty in Java?

Apache StringUtils addresses this problem too.

Failings of the other options:

  • isEmpty() - not null safe. If the string is null, throws an NPE
  • length() == 0 - again not null safe. Also does not take into account whitespace strings.
  • Comparison to EMPTY constant - May not be null safe. Whitespace problem

Granted StringUtils is another library to drag around, but it works very well and saves loads of time and hassle checking for nulls or gracefully handling NPEs.

Reading a date using DataReader

 (DateTime)MyReader["ColumnName"];

OR

Convert.ToDateTime(MyReader["ColumnName"]);

Datatables: Cannot read property 'mData' of undefined

FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.

The following will throw error (no <thead> and <tbody> tags)

<table id="sample-table">
    <tr>
        <th>title-1</th>
        <th>title-2</th>
    </tr>
    <tr>
        <td>data-1</td>
        <td>data-2</td>
    </tr>
</table>

The following will also throw an error (unequal number of columns)

<table id="sample-table">
    <thead>
        <tr>
            <th>title-1</th>
            <th>title-2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>data-1</td>
            <td>data-2</td>
            <td>data-3</td>
        </tr>
    </tbody>
</table>

For more info read more here

How to iterate through table in Lua?

All the answers here suggest to use ipairs but beware, it does not work all the time.

t = {[2] = 44, [4]=77, [6]=88}

--This for loop prints the table
for key,value in next,t,nil do 
  print(key,value) 
end

--This one does not print the table
for key,value in ipairs(t) do 
  print(key,value) 
end

difference between width auto and width 100 percent

Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.

Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.

Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).

First char to upper case

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);

Or, if you feel comfortable with more complex, one-lined java code:

betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

In SQL, how can you "group by" in ranges?

James Curran's answer was the most concise in my opinion, but the output wasn't correct. For SQL Server the simplest statement is as follows:

SELECT 
    [score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR), 
    [number of occurrences] = COUNT(*)
FROM #Scores
GROUP BY Score/10
ORDER BY Score/10

This assumes a #Scores temporary table I used to test it, I just populated 100 rows with random number between 0 and 99.

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

As it turns out, my suspicions were right. The audience aud claim in a JWT is meant to refer to the Resource Servers that should accept the token.

As this post simply puts it:

The audience of a token is the intended recipient of the token.

The audience value is a string -- typically, the base address of the resource being accessed, such as https://contoso.com.

The client_id in OAuth refers to the client application that will be requesting resources from the Resource Server.

The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id and client_secret along with any user credentials that may be required. The Authorization Server validates the client using the client_id and client_secret and returns a JWT.

The JWT will contain an aud claim that specifies which Resource Servers the JWT is valid for. If the aud contains www.myfunwebapp.com, but the client app tries to use the JWT on www.supersecretwebapp.com, then access will be denied because that Resource Server will see that the JWT was not meant for it.

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

Get an object attribute

If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName") - or to elaborate:

user = User()
property = "fullName"
name = getattr(user, property)

Otherwise just use user.fullName.

How to upload (FTP) files to server in a bash script?

echo -e "open <ftp.hostname>\nuser <username> <password>\nbinary\nmkdir New_Folder\nquit"|ftp -nv

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.