Programs & Examples On #Varnish

Varnish is an open source reverse HTTP proxy with extensive caching abilities, i.e. a web accelerator. It is frequently used in front of websites to cache webpages in memory.

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

Passing parameters on button action:@selector

To add to Tristan's answer, the button can also receive (id)event in addition to (id)sender:

- (IBAction) buttonTouchUpInside:(id)sender forEvent:(id)event { .... }

This can be useful if, for example, the button is in a cell in a UITableView and you want to find the indexPath of the button that was touched (although I suppose this can also be found via the sender element).

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

How to compare if two structs, slices or maps are equal?

Since July 2017 you can use cmp.Equal with cmpopts.IgnoreFields option.

func TestPerson(t *testing.T) {
    type person struct {
        ID   int
        Name string
    }

    p1 := person{ID: 1, Name: "john doe"}
    p2 := person{ID: 2, Name: "john doe"}
    println(cmp.Equal(p1, p2))
    println(cmp.Equal(p1, p2, cmpopts.IgnoreFields(person{}, "ID")))

    // Prints:
    // false
    // true
}

Fatal error: Call to a member function fetch_assoc() on a non-object

Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.

java.lang.NoClassDefFoundError: org/json/JSONObject

Add json jar to your classpath

or use java -classpath json.jar ClassName

refer this

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Updated for 2019: As previously suggested, in the latest Eclipse, go to "Install New Software" in the Help Menu and click the "add" button with this URL http://download.eclipse.org/tools/pdt/updates/latest/ that should show the latest release of PHP Development Tools (PDT). You might need to search for "php" or "pdt". For Nightly releases you can use http://download.eclipse.org/tools/pdt/updates/latest-nightly/.

Uploading an Excel sheet and importing the data into SQL Server database

 protected void btnUpload_Click(object sender, EventArgs e)
    {
          if (Page.IsValid)
            {
                bool logval = true;
                if (logval == true)
                {
                    String img_1 = fuUploadExcelName.PostedFile.FileName;
                    String img_2 = System.IO.Path.GetFileName(img_1);
                    string extn = System.IO.Path.GetExtension(img_1);

                    string frstfilenamepart = "";
                    frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
                    UploadExcelName.Value = frstfilenamepart + extn;
                    fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
                    string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
                    GetExcelSheetForEmp(PathName, UploadExcelName.Value);

                }
            }


    }

    private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
    {
        string excelFile = "EmpExcel/" + PathName;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        try
        {

            DataSet dss = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
            objConn = new OleDbConnection(connString);
            objConn.Open();
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return;
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (i == 0)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dss, "TABLE");

                }
                i++;
            }
            grdByExcel.DataSource = dss.Tables[0].DefaultView;
            grdByExcel.DataBind();


        }

        catch (Exception ex)
        {
            ViewState["Fuletypeidlist"] = "0";
            grdByExcel.DataSource = null;
            grdByExcel.DataBind();
        }
        finally
        {
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }

    }

Adding machineKey to web.config on web-farm sites

This should answer:

How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations

Web Farm Deployment Considerations

If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.

With manually generated key values, the settings should be similar to the following example.

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"       

decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.

In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.

Setting Up the Machine Key Using IIS Manager

If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.

Start the management console and then select the web site. Open the machine key configuration: The IIS web site configuration panel

The machine key control panel has the following settings:

The machine key configuration panel

Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.

Click "Generate Keys" under "Actions" on the right side of the panel.

Click "Apply".

and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.

<machineKey  
    validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
                   AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
    decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1"
    decryption="AES"
/>

Please make sure that you have a permanent backup of the machine keys and web.config file

Remove all non-"word characters" from a String in Java, leaving accented characters?

Well, here is one solution I ended up with, but I hope there's a more elegant one...

StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
    char tmpChar = name.charAt( i );
    if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
        result.append( tmpChar );
    }
}

result ends up with the desired result...

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

How to get DropDownList SelectedValue in Controller in MVC

I was having the same issue in asp.NET razor C#

I had a ComboBox filled with titles from an EventMessage, and I wanted to show the Content of this message with its selected value to show it in a label or TextField or any other Control...

My ComboBox was filled like this:

 @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })

In my EventController I had a function to go to the page, in which I wanted to show my ComboBox (which is of a different model type, so I had to use a partial view)?

The function to get from index to page in which to load the partial view:

  public ActionResult EventDetail(int id)
        {

            Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
            //  EventOrg eventOrg = db.EventOrgs.Find(id);
            if (eventOrg == null)
            {

                return HttpNotFound();
            }
            ViewBag.EventBerichten = GetEventBerichtenLijst(id);
            ViewBag.eventOrg = eventOrg;
            return View(eventOrg);
        }

The function for the partial view is here:

 public PartialViewResult InhoudByIdPartial(int id)
        {
            return PartialView(
                db.EventBericht.Where(r => r.EventID == id).ToList());

        }

The function to fill EventBerichten:

        public List<EventBerichten> GetEventBerichtenLijst(int id)
        {
            var eventLijst = db.EventBericht.ToList();
            var berLijst = new List<EventBerichten>();
            foreach (var ber in eventLijst)
            {
                if (ber.EventID == id )
                {
                    berLijst.Add(ber);
                }
            }
            return berLijst;
        }

The partialView Model looks like this:

@model  IEnumerable<STUVF_back_end.Models.EventBerichten>

<table>
    <tr>
        <th>
            EventID
        </th>
        <th>
            Titel
        </th>
        <th>
            Inhoud
        </th>
        <th>
            BerichtDatum
        </th>
        <th>
            BerichtTijd
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EventID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Titel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Inhoud)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtDatum)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtTijd)
            </td>

        </tr>
    }
</table>

VIEUW: This is the script used to get my output in the view

<script type="text/javascript">
    $(document).ready(function () {
        $("#EventBerichten").change(function () {
            $("#log").ajaxError(function (event, jqxhr, settings, exception) {
                alert(exception);
            });

            var BerichtSelected = $("select option:selected").first().text();
            $.get('@Url.Action("InhoudByIdPartial")',
                { EventBerichtID: BerichtSelected }, function (data) {
                    $("#target").html(data);
                });
        });
    });
            </script>
@{
                    Html.RenderAction("InhoudByIdPartial", Model.EventID);
                } 

<fieldset>
                <legend>Berichten over dit Evenement</legend>
                <div>
                    @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
                </div>

                <br />
                <div id="target">

                </div>
                <div id="log">

                </div>
            </fieldset>

Can I force pip to reinstall the current version?

If you have a text file with loads of packages you need to add the -r flag

pip install --upgrade --no-deps --force-reinstall -r requirements.txt

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got the same error for pandas latest version. Then saw this warning

FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.

This shall work for you.

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

Writing/outputting HTML strings unescaped

Supposing your content is inside a string named mystring...

You can use:

@Html.Raw(mystring)

Alternatively you can convert your string to HtmlString or any other type that implements IHtmlString in model or directly inline and use regular @:

@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString

Named placeholders in string formatting

I am the author of a small library that does exactly what you want:

Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);

Or you can chain the arguments:

String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"

How to create UILabel programmatically using Swift?

Create UILabel view outside viewDidLoad class and then add that view to your main view in viewDidLoad method.

lazy var myLabel: UILabel = {


    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "This is label view."
    label.font = UIFont.systemFont(ofSize: 12)
    return label
}()

And then add that view in viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myLabel)

    // Set its constraint to display it on screen
    myLabel.widthAnchor.constraint(equalToConstant:  200).isActive = true
    myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

Endless loop in C/C++

Well, there is a lot of taste in this one. I think people from a C background are more likely to prefer for(;;), which reads as "forever". If its for work, do what the locals do, if its for yourself, do the one that you can most easily read.

But in my experience, do { } while (1); is almost never used.

How do I convert an existing callback API to promises?

The callback style function always like this(almost all function in node.js is this style):

//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))

This style has same feature:

  1. the callback function is passed by last argument.

  2. the callback function always accept the error object as it's first argument.

So, you could write a function for convert a function with this style like this:

const R =require('ramda')

/**
 * A convenient function for handle error in callback function.
 * Accept two function res(resolve) and rej(reject) ,
 * return a wrap function that accept a list arguments,
 * the first argument as error, if error is null,
 * the res function will call,else the rej function.
 * @param {function} res the function which will call when no error throw
 * @param {function} rej the function which will call when  error occur
 * @return {function} return a function that accept a list arguments,
 * the first argument as error, if error is null, the res function
 * will call,else the rej function
 **/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
    R.propEq('err', null),
    R.compose(
        res,
        R.prop('data')
    ),
    R.compose(
        rej,
        R.prop('err')
    )
)({err, data})

/**
 * wrap the callback style function to Promise style function,
 * the callback style function must restrict by convention:
 * 1. the function must put the callback function where the last of arguments,
 * such as (arg1,arg2,arg3,arg...,callback)
 * 2. the callback function must call as callback(err,arg1,arg2,arg...)
 * @param {function} fun the callback style function to transform
 * @return {function} return the new function that will return a Promise,
 * while the origin function throw a error, the Promise will be Promise.reject(error),
 * while the origin function work fine, the Promise will be Promise.resolve(args: array),
 * the args is which callback function accept
 * */
 const toPromise = (fun) => (...args) => new Promise(
    (res, rej) => R.apply(
        fun,
        R.append(
            checkErr(res, rej),
            args
        )
    )
)

For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply) and append(like javascript function.prototype.push ). So, we could convert the a callback style function to promise style function now:

const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
    .then(
        (files) => console.log(files),
        (err) => console.log(err)
    )

toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).

Hope this answer is useful for you.

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

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

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

The bulk of the work is explained here:

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

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

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

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

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

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

};

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

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

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

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

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

How to convert AAR to JAR

.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.

If you needed to, you could extract it to your filesystem and then repackage it as a jar.

1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)

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

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

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

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

Why do I need 'b' to encode a string with Base64?

If the string is Unicode the easiest way is:

import base64                                                        

a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))

# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'

b = base64.b64decode(a).decode("utf-8", "ignore")                    

print(b)
# b :complex string: ñáéíóúÑ

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

Is it possible that one domain name has multiple corresponding IP addresses?

Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.

Correct way to use Modernizr to detect IE?

You can use Modernizr to detect simply IE or not IE, by checking for SVG SMIL animation support.

If you've included SMIL feature detection in your Modernizr setup, you can use a simple CSS approach, and target the .no-smil class that Modernizr applies to the html element:

html.no-smil {
  /* IE/Edge specific styles go here - hide HTML5 content and show Flash content */
}

Alternatively, you could use Modernizr with a simple JavaScript approach, like so:

if ( Modernizr.smil ) {
  /* set HTML5 content */
} else {
  /* set IE/Edge/Flash content */
}

Bear in mind, IE/Edge might someday support SMIL, but there are currently no plans to do so.

For reference, here's a link to the SMIL compatibility chart at caniuse.com.

Debugging JavaScript in IE7

If you still need to Debug IE 7, the emulation mode of IE 11 is working pretty well.

Go to menu: Dev Tools, then to emulation and set it. It also gives error line information.

Array to Collection: Optimized code

Another way to do it:

Collections.addAll(collectionInstance,array);

Print array to a file

echo "<pre>: ";      
print_r($this->array_to_return_string($array));
protected function array_to_return_string($param) {
    $str="[";
    if($param){
        foreach ($param as $key => $value) {
            if(is_array($value) && $value){
                $strx=$this->array_to_return_string($value);
                $str.="'$key'=>$strx";
            }else{
                $str.="'$key'=>'$value',";
            }
        }
    }
    $str.="],";
    return $str;
}

How do I add a new sourceset to Gradle?

Update for 2021:

A lot has changed in 8ish years. Gradle continues to be a great tool. Now there's a whole section in the docs dedicated to configuring Integration Tests. I recommend you read the docs now.

Original Answer:

This took me a while to figure out and the online resources weren't great. So I wanted to document my solution.

This is a simple gradle build script that has an intTest source set in addition to the main and test source sets:

apply plugin: "java"

sourceSets {
    // Note that just declaring this sourceset creates two configurations.
    intTest {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
    }
}

configurations {
    intTestCompile.extendsFrom testCompile
    intTestRuntime.extendsFrom testRuntime
}

task intTest(type:Test){
    description = "Run integration tests (located in src/intTest/...)."
    testClassesDir = project.sourceSets.intTest.output.classesDir
    classpath = project.sourceSets.intTest.runtimeClasspath
}

Disable/enable an input with jQuery?

Use like this,

 $( "#id" ).prop( "disabled", true );

 $( "#id" ).prop( "disabled", false );

Fixed positioning in Mobile Safari

See Google's solution to this problem. You basically have to scroll content yourself using JavaScript. Sencha Touch also provides a library for getting this behavior in a very performant manor.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

Getting Chrome to accept self-signed localhost certificate

Fix for Chrome on Windows.

First, you need to export the certificate.

  • Locate the url in the browser. “https” segment of the url will be crossed out with the red line and there will be a lock symbol to the left.
  • Right click on the crossed-out "https" segment.
  • You will see an information window with various information
  • Click “details”.
  • Export the certificate, follow directions accept default settings.

To import

  • Go to Chrome Settings
  • Click on "advanced settings"
  • Under HTTPS/SSL click to "Manage Certificates"
  • Go to "Trusted Root Certificate Authorities"
  • Click to "Import"
  • There will be a pop up window that will ask you if you want to install this certificate. Click "yes".

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

swift 3.0 Data to String?

I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:

var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

How to tell whether a point is to the right or left side of a line

I wanted to provide with a solution inspired by physics.

Imagine a force applied along the line and you are measuring the torque of the force about the point. If the torque is positive (counterclockwise) then the point is to the "left" of the line, but if the torque is negative the point is the "right" of the line.

So if the force vector equals the span of the two points defining the line

fx = x_2 - x_1
fy = y_2 - y_1

you test for the side of a point (px,py) based on the sign of the following test

var torque = fx*(py-y_1)-fy*(px-x_1)
if  torque>0  then
     "point on left side"
else if torque <0 then
     "point on right side"  
else
     "point on line"
end if

How to import an existing project from GitHub into Android Studio

Unzip the github project to a folder. Open Android Studio. Go to File -> New -> Import Project. Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.

P.S: In some versions of Android Studio a certain error occurs-
error:package android.support.v4.app does not exist.
To fix it go to Gradle Scripts->build.gradle(Module:app) and the add the dependecies:

dependencies {      
    compile fileTree(dir: 'libs', include: ['*.jar'])  
    compile 'com.android.support:appcompat-v7:21.0.3'  
}

Enjoy working in Android Studio

Maven and adding JARs to system scope

You will need to add the jar to your local maven repository. Alternatively (better option) specify the proper repository (if one exists) so it can be automatically downloaded by maven

In either case, remove the <systemPath> tag from the dependency

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

Implementing IDisposable correctly

The following example shows the general best practice to implement IDisposable interface. Reference

Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.

public class DisposeExample
{
    // A base class that implements IDisposable. 
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources. 
    public class MyResource: IDisposable
    {
        // Pointer to an external unmanaged resource. 
        private IntPtr handle;
        // Other managed resource this class uses. 
        private Component component = new Component();
        // Track whether Dispose has been called. 
        private bool disposed = false;

        // The class constructor. 
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable. 
        // Do not make this method virtual. 
        // A derived class should not be able to override this method. 
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method. 
            // Therefore, you should call GC.SupressFinalize to 
            // take this object off the finalization queue 
            // and prevent finalization code for this object 
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios. 
        // If disposing equals true, the method has been called directly 
        // or indirectly by a user's code. Managed and unmanaged resources 
        // can be disposed. 
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed. 
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called. 
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed 
                // and unmanaged resources. 
                if(disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up 
                // unmanaged resources here. 
                // If disposing is false, 
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;

            }
        }

        // Use interop to call the method necessary 
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code. 
        // This destructor will run only if the Dispose method 
        // does not get called. 
        // It gives your base class the opportunity to finalize. 
        // Do not provide destructors in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here. 
            // Calling Dispose(false) is optimal in terms of 
            // readability and maintainability.
            Dispose(false);
        }
    }
    public static void Main()
    {
        // Insert code here to create 
        // and use the MyResource object.
    }
}

javascript clear field value input

HTML:

<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>

JS:

function clearField(input) {
  if(input.value=="Name") { //Only clear if value is "Name"
    input.value = "";
  }
}
function fillField(input) {
    if(input.value=="") {
        input.value = "Name";
    }
}

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

How to check if a radiobutton is checked in a radiogroup in Android?

I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:

  1. MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private RadioGroup genderRadioGroup;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        //Initialize Radio Group And Submit Button
        genderRadioGroup=findViewById(R.id.gender_radiogroup);
        AppCompatButton submit = findViewById(R.id.btnSubmit);
    
        //Submit Radio Group using Submit Button
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Check Gender radio Group For Selected Radio Button
                if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                    Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
                }else{//Radio Button Is Checked
                    RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                    gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
                }
                //Validate
                if (validateInputs()) {
                    //code to proceed when Radio button is checked
                }
            }
        }
        //Validation - No process is initialized if no Radio button is checked
        private boolean validateInputs() {
            if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
                return false;
            }
            return true;
        }
    }
    
  2. In activity_main.xml:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/gender"/>
    
        <RadioGroup
                android:id="@+id/gender_radiogroup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
            <RadioButton
                    android:id="@+id/male"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/male"/>
    
            <RadioButton
                    android:id="@+id/female"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/female""/>
    
        </RadioGroup>
    
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnSubmit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/submit"/>
    
    </LinearLayout>
    

If no gender radio button is selected, then the code to proceed will not run.

I hope this helps.

Is there a MessageBox equivalent in WPF?

If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows

here is xaml :

<Window x:Class="popup.MessageboxNew"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:popup"
        mc:Ignorable="d"
        Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
        >
    <Window.Resources>

    </Window.Resources>
    <Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Window.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <Grid Loaded="FrameworkElement_OnLoaded">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border Name="Mask" CornerRadius="8" Background="White" />
            <Grid x:Name="Grid" Background="White">
                <Grid.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=Mask}"/>
                </Grid.OpacityMask>
                <StackPanel Name="StackPanel" >
                    <TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14" 
                             Foreground="Black" FontWeight="Normal"
                             Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
                    <DockPanel Name="ContentHost" Margin="0,10,0,10" >
                        <TextBlock Margin="10" Name="Textbar"></TextBlock>
                    </DockPanel>
                    <DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
                        <Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
                        <Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
                    </DockPanel>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

for cs of this file :

public partial class MessageboxNew : Window
    {
        public MessageboxNew()
        {
            InitializeComponent();
            //second time show error solved
            if (Application.Current == null) new Application();
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.MouseDown += delegate { DragMove(); };
        }
    }

then create a class to use this :

public class Mk_MessageBox
{
    public static bool? Show(string title, string text)
    {
        MessageboxNew msg = new MessageboxNew
        {
            TitleBar = {Text = title},
            Textbar = {Text = text}
        };
        msg.noBtn.Focus();
        return msg.ShowDialog();
    }
}

now you can create your message box like this:

var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
            if (result == true)
            {
                // whatever
            }

copy this to App.xaml inside

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
            <!-- Accent and AppTheme setting -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />

            <!--two new guys-->
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />

            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

--------------IMAGE of Result-----------------

My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/

for logic how can i make my own messagebox

how to calculate percentage in python

This is because (100/500) is an integer expression yielding 0.

Try

per = 100.0 * tota / 500

there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.

Is there such a thing as min-font-size and max-font-size?

Please note that setting font-sizing with px is not recommended due to accessibility concerns:

"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)

A more accessible approach is to set font-size: 100% in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em or rem), for example with a @media query.

(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)

Get SSID when WIFI is connected

I found interesting solution to get SSID of currently connected Wifi AP. You simply need to use iterate WifiManager.getConfiguredNetworks() and find configuration with specific WifiInfo.getNetworkId()

My example

in Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION I'm getting current connection state from intent

NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
nwInfo.getState()

If NetworkInfo.getState is equal to NetworkInfo.State.CONNECTED then i can get current WifiInfo object

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();

And after that

public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {

    List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();

    for (int index = 0; index < listOfConfigurations.size(); index++) {
        WifiConfiguration configuration = listOfConfigurations.get(index);
        if (configuration.networkId == wifiInfo.getNetworkId()) {
            return configuration.SSID;
        }
    }

    return null;
}

And very important thing this method doesn't require Location nor Location Permisions

In API29 Google redesigned Wifi API so this solution is outdated for Android 10.

How to set default value for HTML select?

Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

How to use a filter in a controller?

Use below code if we want to add multiple conditions, instead of single value in javascript angular filter:

var modifiedArray = $filter('filter')(array,function(item){return (item.ColumnName == 'Value1' || item.ColumnName == 'Value2');},true)

How can I run an external command asynchronously from Python?

This is covered by Python 3 Subprocess Examples under "Wait for command to terminate asynchronously":

import asyncio

proc = await asyncio.create_subprocess_exec(
    'ls','-lha',
    stdout=asyncio.subprocess.PIPE,
    stderr=asyncio.subprocess.PIPE)

# do something else while ls is working

# if proc takes very long to complete, the CPUs are free to use cycles for 
# other processes
stdout, stderr = await proc.communicate()

The process will start running as soon as the await asyncio.create_subprocess_exec(...) has completed. If it hasn't finished by the time you call await proc.communicate(), it will wait there in order to give you your output status. If it has finished, proc.communicate() will return immediately.

The gist here is similar to Terrels answer but I think Terrels answer appears to overcomplicate things.

See asyncio.create_subprocess_exec for more information.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

How can I cast int to enum?

I need two instructions:

YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum
if (Enum.IsDefined(typeof(YourEnum), possibleEnum))
{
    // Value exists in YourEnum
}

Best way to list files in Java, sorted by Date Modified?

Imports :

org.apache.commons.io.comparator.LastModifiedFileComparator

Apache Commons

Code :

public static void main(String[] args) throws IOException {
        File directory = new File(".");
        // get just files, not directories
        File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);

        System.out.println("Default order");
        displayFiles(files);

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        System.out.println("\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)");
        displayFiles(files);

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        System.out.println("\nLast Modified Descending Order (LASTMODIFIED_REVERSE)");
        displayFiles(files);

    }

Convert datetime to Unix timestamp and convert it back in python

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

Get user's current location

Try this code using the hostip.info service:

$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;

// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);

echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);

How do I display a decimal value to 2 decimal places?

If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12...

decimalVar.ToString("n2");

Font-awesome, input type 'submit'

You can use button classes btn-link and btn-xs with type submit, which will make a small invisible button with an icon inside of it. Example:

<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
    <i class="fa fa-times text-danger"></i>
</button>

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

Your problem is within the php5-dev package. I guess you went from php5.2 on an older linux version to php5.3. I did the same thing, and when I managed to install php 5.3 there was a conflict with php5-dev. For some reason it doesn't get upgraded to the new version. Dunno why is that and I don't care, however this makes your extension compiled with the older API version, while php ofc is with the newer api version. What I did to solve this problem was:

I removed php5-dev with sudo apt-get remove php5-dev, then I ran sudo apt-get autoremove to get rid of the leftovers that were giving me the trouble, and after that I just installed php5-dev again. sudo apt-get install php5-dev.

Once that was done, I removed my memcache with sudo pecl uninstall memcache and installed it again sudo pecl install memcache. Now both the module and the php had the same api version so I knew right away that I had the issue solved :)

Hope it helps.

Concatenate two char* strings in a C program

strcat attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.

If all you want to do is print two strings out

printf("%s%s",str1,str2);

Would do.

You could do something like

char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
strcpy(str1,"SSSS");
strcat(str1,str2);

to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free str1 at the end).

Auto start node.js server on boot

Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.

PHP foreach with Nested Array?

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Error message Strict standards: Non-static method should not be called statically in php

return false is usually meant to terminate the object creation with a failure. It is as simple as that.

Can't import org.apache.http.HttpResponse in Android Studio

Use This:-

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

How can I calculate the difference between two dates?

To find the difference, you need to get the current date and the date in the future. In the following case, I used 2 days for an example of the future date. Calculated by:

2 days * 24 hours * 60 minutes * 60 seconds. We expect the number of seconds in 2 days to be 172,800.

// Set the current and future date
let now = Date()
let nowPlus2Days = Date(timeInterval: 2*24*60*60, since: now)

// Get the number of seconds between these two dates
let secondsInterval = DateInterval(start: now, end: nowPlus2Days).duration

print(secondsInterval) // 172800.0

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

JavaScript - Get minutes between two dates

A simple function to perform this calculation:

function getMinutesBetweenDates(startDate, endDate) {
    var diff = endDate.getTime() - startDate.getTime();
    return (diff / 60000);
}

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Align div right in Bootstrap 3

Bootstrap 4+ has made changes to the utility classes for this. From the documentation:

Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.

So use the .float-right (or a size equivalent such as .float-lg-right) instead of .pull-right for your right alignment if you're using a newer Bootstrap version.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

As for second question - you can use Fiddler filters to set response X-Frame-Options header manually to something like ALLOW-FROM *. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).

Using HTML5/JavaScript to generate and save a file

You can generate a data URI. However, there are browser-specific limitations.

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

Android: remove notification from notification bar

If you are generating Notification from a Service that is started in the foreground using

startForeground(NOTIFICATION_ID, notificationBuilder.build());

Then issuing

notificationManager.cancel(NOTIFICATION_ID);

does't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:

1> Using stopForeground( false ) inside service:

stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);

2> Destroy that service class with calling activity:

Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
    ServiceCallingActivity.activity.finish();
}
context.stopService(i);

Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!

Set TextView text from html-formatted string resource in XML

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

<![CDATA[ ...raw html... ]]>

Example:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-)

How to sort by column in descending order in Spark SQL?

PySpark only

I came across this post when looking to do the same in PySpark. The easiest way is to just add the parameter ascending=False:

df.orderBy("col1", ascending=False).show(10)

Reference: http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame.orderBy

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

Appending a list or series to a pandas DataFrame as a row?

Converting the list to a data frame within the append function works, also when applied in a loop

import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))

Fully change package name including company domain

I have not changed any package name. The following two steps worked for me. After doing the following, the application was installed as a NEW one , eventhough there was two applications with the same package name.

1) In the build.gradle

applicationId "mynew.mynewpackage.com"

2) In the AndroidManifest.xml android:authorities="mynew.mynewpackage.com.fileprovider"

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

Angular - ui-router get previous state

Ok, I know that I am late to the party here, but I am new to angular. I am trying to make this fit into the John Papa style guide here. I wanted to make this reusable so I created in a block. Here is what I came up with:

previousStateProvider

(function () {
'use strict';

angular.module('blocks.previousState')
       .provider('previousState', previousStateProvider);

previousStateProvider.$inject = ['$rootScopeProvider'];

function previousStateProvider($rootScopeProvider) {
    this.$get = PreviousState;

    PreviousState.$inject = ['$rootScope'];

    /* @ngInject */
    function PreviousState($rootScope) {
        $rootScope.previousParms;
        $rootScope.previousState;
        $rootScope.currentState;

        $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
            $rootScope.previousParms = fromParams;
            $rootScope.previousState = from.name;
            $rootScope.currentState = to.name;
        });
    }
}
})();

core.module

(function () {
'use strict';

angular.module('myApp.Core', [
    // Angular modules 
    'ngMessages',
    'ngResource',

    // Custom modules 
    'blocks.previousState',
    'blocks.router'

    // 3rd Party Modules
]);
})();

core.config

(function () {
'use strict';

var core = angular.module('myApp.Core');

core.run(appRun);

function appRun(previousState) {
    // do nothing. just instantiating the state handler
}
})();

Any critique on this code will only help me, so please let me know where I can improve this code.

What is the difference between README and README.md in GitHub projects?

.md stands for markdown and is generated at the bottom of your github page as html.

Typical syntax includes:

Will become a heading
==============

Will become a sub heading
--------------

*This will be Italic*

**This will be Bold**

- This will be a list item
- This will be a list item

    Add a indent and this will end up as code

For more details: http://daringfireball.net/projects/markdown/

How to execute Python code from within Visual Studio Code

To extend vlad2135's answer (read his first); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).

Basically, when you click the gear icon, it creates a launch.json file in your .vscode directory in your workspace. You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting. Here's an example file:

File launch.json

You'll notice something cool after you generate it. It automatically created a bunch of configurations (most of mine are cut off; just scroll to see them all) with different settings and extra features for different libraries or environments (like Django).

The one you'll probably end up using the most is Python; which is a plain (in my case C)Python debugger and is easiest to work with settings wise.

I'll make a short walkthrough of the JSON attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.

  • name: The name of the configuration. A useful example of why you would change it is if you have two Python configurations which use the same type of config, but different arguments. It's what shows up in the box you see on the top left (my box says "python" since I'm using the default Python configuration).
  • type: Interpreter type. You generally don't want to change this one.
  • request: How you want to run your code, and you generally don't want to change this one either. Default value is "launch", but changing it to "attach" allows the debugger to attach to an already running Python process. Instead of changing it, add a configuration of type attach and use that.
  • stopOnEntry: Python debuggers like to have an invisible break-point when you start the program so you can see the entry-point file and where your first line of active code is. It drives some C#/Java programmers like me insane. false if you don't want it, true otherwise.
  • pythonPath: The path to your install of Python. The default value gets the extension level default in the user/workspace settings. Change it here if you want to have different Pythons for different debug processes. Change it in workspace settings if you want to change it for all debug processes set to the default configuration in a project. Change it in user setting to change where the extension finds Pythons across all projects. (4/12/2017 The following was fixed in extension version 0.6.1). Ironically enough, this gets auto-generated wrong. It auto-generates to "${config.python.pythonPath}" which is deprecated in the newer Visual Studio Code versions. It might still work, but you should use "${config:python.pythonPath}" instead for your default first python on your path or Visual Studio Code settings. (4/6/2017 Edit: This should be fixed in the next release. The team committed the fix a few days ago.)
  • program: The initial file that you debugger starts up when you hit run. "${workspaceRoot}" is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder). Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to "${file}" which will start debugging at the file you have open and in focus in the moment you hit debug.
  • cwd: The current working directory folder of the project you're running. Usually you'll just want to leave this "${workspaceRoot}".
  • debugOptions: Some debugger flags. The ones in the picture are default flags, you can find more flags in the python debugger pages, I'm sure.
  • args: This isn't actually a default configuration setting, but a useful one nonetheless (and probably what the OP was asking about). These are the command line arguments that you pass in to your program. The debugger passes these in as though they you had typed: python file.py [args] into your terminal; passing each JSON string in the list to the program in order.

You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.

You can go here for the extension's own documentation on launch options, with both optional and required attributes.

You can click the Add Configuration button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.

Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.

Pro tip: Different people on your team use different IDEs and they probably don't need your configuration files. Visual Studio Code nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add directory .vscode/ to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)!

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

How to clear the cache in NetBeans

In Window 7 the cache is located at C:/Users/USERNAME/AppData/Local/NetBeans/Cache

How to check if an environment variable exists and get its value?

[ -z "${DEPLOY_ENV}" ] checks whether DEPLOY_ENV has length equal to zero. So you could run:

if [[ -z "${DEPLOY_ENV}" ]]; then
  MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
  MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi

# or using a short-hand version

[[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"

# or even shorter use

MyVar="${DEPLOY_ENV:-default_value}"

What are Java command line options to set to allow JVM to be remotely debugged?

Command Line

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=PORT_NUMBER

Gradle

gradle bootrun --debug-jvm

Maven

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

Why do we need middleware for async flow in Redux?

Redux can't return a function instead of an action. It's just a fact. That's why people use Thunk. Read these 14 lines of code to see how it allows the async cycle to work with some added function layering:

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

https://github.com/reduxjs/redux-thunk

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Where do I find the line number in the Xcode editor?

In Preferences->Text Editing-> Show: Line numbers you can enable the line numbers on the left hand side of the file.

Check difference in seconds between two times

I use this to avoid negative interval.

var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;

Azure SQL Database "DTU percentage" metric

A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.

Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.

The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.

From down toward the bottom of this announcement:

For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.

As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.

How to change line color in EditText

Its pretty simple (Required: Minimum API 21)...

  1. Go to your xml and select the EditText field
  2. On the right side, you can see the 'Attributes' window. Select 'View All Attributes'
  3. Just search for 'tint'
  4. And add/change the 'backgroundTint' to a desired color hex (say #FF0000)

enter image description here

enter image description here

Keep Coding........ :)

Switch statement fall-through...should it be allowed?

It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit.

An example, to update old versions of some data:

switch (version) {
    case 1:
        // Update some stuff
    case 2:
        // Update more stuff
    case 3:
        // Update even more stuff
    case 4:
        // And so on
}

Changing the resolution of a VNC session in linux

As far as I know there's no way to change the client's resolution just using VNC, as it is just a "monitor mirroring" application.

TightVNC however (which is a VNC client and server application) can resize the screen on the client side, i.e. making everything a little smaller (similar to image resizing techniques in graphics programs). That should work if you don't use too small font sizes. VNC should theoretically be compatible between different VNC applications.

How to write the code for the back button?

You need to tell the browser you are using javascript:

<a href="javascript:history.back(1)">Back</a> 

Also, your input element seems out of place in your code.

CMake: How to build external projects and include their targets

I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.

"CMakeLists.txt"

cmake_minimum_required(VERSION 3.10.2)

# Target Project
project (ClientProgram)

# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers


# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables


# This Project Depends on External Project(s) 
include (ExternalProject)

# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL             http://myproject.com/MyLibrary.tgz
URL_HASH        SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server

# Begin: Download Source from GIT Repository
#    GIT_REPOSITORY  https://github.com/<project>.git
#    GIT_TAG         <Refer github.com releases -> Tags>
#    GIT_SHALLOW     ON
# End: Download Source from GIT Repository

# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS      -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments    
)

# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory

# Acquire Installation Directory of 
ExternalProject_Get_Property (${libTLS} install_dir)

# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)

# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)

# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library

# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component

# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

For debugging purposes, you could use print(repr(data)).

To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.

To print Unicode to Windows console, you could use win-unicode-console package.

Where can I find the .apk file on my device, when I download any app and install?

You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.

In Java, how do you determine if a thread is running?

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.

'negative' pattern matching in python

and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)

is working.

How to check "hasRole" in Java Code with Spring Security?

The @gouki answer is best!

Just a tip of how spring really do this.

There is a class named SecurityContextHolderAwareRequestWrapper which implements the ServletRequestWrapper class.

The SecurityContextHolderAwareRequestWrapper overrides the isUserInRole and search user Authentication (which is managed by Spring) to find if user has a role or not.

SecurityContextHolderAwareRequestWrapper the code is as:

    @Override
    public boolean isUserInRole(String role) {
        return isGranted(role);
    }

 private boolean isGranted(String role) {
        Authentication auth = getAuthentication();

        if( rolePrefix != null ) {
            role = rolePrefix + role;
        }

        if ((auth == null) || (auth.getPrincipal() == null)) {
            return false;
        }

        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

        if (authorities == null) {
            return false;
        }

        //This is the loop which do actual search
        for (GrantedAuthority grantedAuthority : authorities) {
            if (role.equals(grantedAuthority.getAuthority())) {
                return true;
            }
        }

        return false;
    }

How to run TypeScript files from command line?

Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.

#!/usr/bin/env bash

NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc

export TSC="$NODEPATH/tsc"
export NODE="$NODEPATH/node"

TSCFILE=$1 # only parameter is the name of the ts file you created.

function show_usage() {
    echo "ts2node [ts file]"
    exit 0
}

if [ "$TSCFILE" == "" ]
then
    show_usage;
fi

JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"

$TSC $TSCFILE && $NODE $JSFILE

You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:

# tsrun myscript.ts

Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.

How to check all checkboxes using jQuery?

One checkbox to rule them all

For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin.

Feel free to check the examples on documentation page.


For this question example all you need to do is:

$( "#checkAll" ).checkall({
    target: "input:checkbox"
});

Isn't that clear and simple?

How to open existing project in Eclipse

Right click in navigator-Import-existing project..-select the base directory of your project

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

Add unique constraint to combination of two columns

In my case, I needed to allow many inactives and only one combination of two keys active, like this:

UUL_USR_IDF  UUL_UND_IDF    UUL_ATUAL
137          18             0
137          19             0
137          20             1
137          21             0

This seems to work:

CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;

Here are my test cases:

SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137

insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN

DELETE FROM USER_UND WHERE UUL_USR_ID = 137

insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN

Call one constructor from another

Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.

  class BaseClass
{
    public BaseClass():this(10)
    {
    }
    public BaseClass(int val)
    {
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            new BaseClass();
            ReadLine();
        }
    }

Count records for every month in a year

Try This query:

SELECT 
  SUM(CASE datepart(month,ARR_DATE) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ARR_DATE) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ARR_DATE) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ARR_DATE) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ARR_DATE) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ARR_DATE) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ARR_DATE) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ARR_DATE) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ARR_DATE) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,ARR_DATE) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,ARR_DATE) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,ARR_DATE) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,ARR_DATE) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    sometable
WHERE
  ARR_DATE BETWEEN '2012/01/01' AND '2012/12/31' 

What is the maximum float in Python?

sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.

Remove all occurrences of a value from a list?

About the speed!

import time
s_time = time.time()

print 'start'
a = range(100000000)
del a[:]
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 3.25

s_time = time.time()
print 'start'
a = range(100000000)
a = []
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 2.11

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

String replace a Backslash

sSource = sSource.replace("\\/", "/");
  • String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
  • replaceAll(..) uses regex. You don't need that.

Java String array: is there a size of method?

Also, it's probably useful to note that if you have a multiple dimensional Array, you can get the respective dimension just by appending a '[0]' to the array you are querying until you arrive at the appropriate axis/tuple/dimension.

This is probably better explained with the following code:

public class Test {
    public static void main(String[] args){
        String[][] moo = new String[5][12];

        System.out.println(moo.length); //Prints the size of the First Dimension in the array
        System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
    }

}

Which produces the output:

5
12

Flask Python Buttons

I think this solution is good:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        if form.submit.data:
            pass
        elif form.submit2.data:
            pass
    return render_template('contact.html', form=form)

Form:

class ContactForm(FlaskForm):

    submit = SubmitField('Do this')
    submit2 = SubmitField('Do that')

How to create an object property from a variable value in JavaScript?

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts "whatever")

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

Is Java a Compiled or an Interpreted programming language ?

The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.

As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.

These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.

JQuery html() vs. innerHTML

Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!

Run this in internet explorer 7 or 8 and you'll see.

jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!

There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.

<html>

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>   

        <script>
            $(function() {

                // the following two blocks of HTML are identical except the P tag is outside the form in the first case
                var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
                var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";

                // <FORM> tag nested within <P>
                RunTest("<FORM> tag nested within <P> tag", html1);                 // succeeds in Internet Explorer    
                RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1);     // fails with added new line in Internet Explorer


                // <P> tag nested within <HTML>
                RunTest("<P> tag nested within <FORM> tag", html2);                 // succeeds in Internet Explorer
                RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2);     // succeeds in Internet Explorer even with \n

            });

            function RunTest(testName, html) {

                // run with jQuery
                $("#placeholder").html(html);
                var jqueryDOM = $('#placeholder').html();
                var jqueryFormSerialize = $("#placeholder form").serialize();

                // run with innerHTML
                $("#placeholder")[0].innerHTML = html;

                var innerHTMLDOM = $('#placeholder').html();
                var innerHTMLFormSerialize = $("#placeholder form").serialize();

                var expectedSerializedValue = "field1=111&field2=222";

                alert(  'TEST NAME: ' + testName + '\n\n' +
                    'The HTML :\n"' + html + '"\n\n' +
                    'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
                    'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +

                    'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +

                    'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
                    'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +

                    'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
                    'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") 

                    );
            }

        </script>
    </head>

    <div id="placeholder">
        This is #placeholder text will 
    </div>

</html>

ArrayList: how does the size increase?

static int getCapacity(ArrayList<?> list) throws Exception {
            Field dataField = ArrayList.class.getDeclaredField("elementData");
            dataField.setAccessible(true);
            return ((Object[]) dataField.get(list)).length;
    }

use the above method to check the size when the arraylist is being modified.

Switching from zsh to bash on OSX, and back again?

if it is just a temporary switch

you can use exec as mentioned above, but for more of a permanent solution.

you can use chsh -s /bin/bash (to switch to bash) and chsh -s /bin/zsh (to switch to zsh)

Tomcat 7 is not running on browser(http://localhost:8080/ )

You can run below commands.

 ./catalina.sh run

Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)

How can I Remove .DS_Store files from a Git repository?

There are a few solutions to resolve this problem. To avoid creating .DS_Store files, do not to use the OS X Finder to view folders. An alternative way to view folders is to use UNIX command line. To remove the .DS_Store files a third-party product called DS_Store Terminator can be used. To delete the .DS_Store files from the entire system a UNIX shell command can be used. Launch Terminal from Applications:Utilities At the UNIX shell prompt enter the following UNIX command: sudo find / -name ".DS_Store" -depth -exec rm {} \; When prompted for a password enter the Mac OS X Administrator password.

This command is to find and remove all occurrences of .DS_Store starting from the root (/) of the file system through the entire machine. To configure this command to run as a scheduled task follow the steps below: Launch Terminal from Applications:Utilities At the UNIX shell prompt enter the following UNIX command:

sudo crontab -e When prompted for a password enter the Mac OS X Administrator password. Once in the vi editor press the letter I on your keyboard once and enter the following:

15 1 * * * root find / -name ".DS_Store" -depth -exec rm {} \;

This is called crontab entry, which has the following format:

Minute Hour DayOfMonth Month DayOfWeek User Command.

The crontab entry means that the command will be executed by the system automatically at 1:15 AM everyday by the account called root.

The command starts from find all the way to . If the system is not running this command will not get executed.

To save the entry press the Esc key once, then simultaneously press Shift + z+ z.

Note: Information in Step 4 is for the vi editor only.

Update rows in one table with data from another table based on one column in each being equal

If you want to update matching rows in t1 with data from t2 then:

update t1
set (c1, c2, c3) = 
(select c1, c2, c3 from t2
 where t2.user_id = t1.user_id)
where exists
(select * from t2
 where t2.user_id = t1.user_id)

The "where exists" part it to prevent updating the t1 columns to null where no match exists.

What is the difference between json.load() and json.loads() functions

In python3.7.7, the definition of json.load is as below according to cpython source code:

def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

json.load actually calls json.loads and use fp.read() as the first argument.

So if your code is:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

It's the same to do this:

with open (file) as fp:
    json.load(fp)

But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
    containing a JSON document) to a Python object.

    ...

    """
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

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

Go to Tools-->Firebase in your Android Studio and click on Connect your app to Firebase. They will set it up for you.

JPA - Returning an auto generated id after persist()

This is how I did it. You can try

    public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         ABC.setId(0);
         return abcDao.insertABC(abc);
    }
}

How to allow users to check for the latest app version from inside the app?

To save time writing for check new version update for android app, I written it as library and open source at https://github.com/winsontan520/Android-WVersionManager

How to mock private method for testing using PowerMock?

i know a way ny which you can call you private function to test in mockito

@Test
    public  void  commandEndHandlerTest() throws  Exception
    {
        Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
        retryClientDetail_privateMethod.setAccessible(true);
        retryClientDetail_privateMethod.invoke(yourclass.class, null);
    }

excel VBA run macro automatically whenever a cell is changed

In an attempt to find a way to make the target cell for the intersect method a name table array, I stumbled across a simple way to run something when ANY cell or set of cells on a particular sheet changes. This code is placed in the worksheet module as well:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 0 Then
'mycode here
end if
end sub

How to get xdebug var_dump to show full object/array

I know this is a super old post, but I figured this may still be helpful.

If you're comfortable with reading json format you could replace your var_dump with:

return json_encode($myvar);

I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.

Also, because the json_encoded data is a string it means you can write it to the error log easily

error_log(json_encode($myvar));

It probably isn't the best choice for every situation, but it's a choice!

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

"Javac" doesn't work correctly on Windows 10

I added below Path in environment variable

C:\Program Files\Java\jdk1.8.0_91\bin

and then compiled the program but got the error then I restarted the system and again compiled the program

This time it worked :)

Fiddler not capturing traffic from browsers

I had the same problem, when i disabled chrome extension called ZenMate Proxy extension that fixed the problem

How can I return pivot table output in MySQL?

There is a tool called MySQL Pivot table generator, it can help you create web based pivot table that you can later export to excel(if you like). it can work if your data is in a single table or in several tables .

All you need to do is to specify the data source of the columns (it supports dynamic columns), rows , the values in the body of the table and table relationship (if there are any) MySQL Pivot Table

The home page of this tool is http://mysqlpivottable.net

Xcode 10: A valid provisioning profile for this executable was not found

[edit] Note 2020: I used to manual sign this project. In projects where I automatically signed, I never had this issue. [/edit]

I had the same problem, and spent hours searching for an answer, removing profiles, cleaning project, and so on.

Have you distributed your app? You need to switch back to your developer profile, but not in General under the project settings, but in Build settings.

Under Signing, look at your Code Signing Identity.

Make sure that both your Debug and Release are set your iOS Developer, and not iOS Distribution; or your iOS Developer Provisioning profile, if not set to the automatic values.

The same goes with Provisioning Profile. It should be your developing profile, and not your distribution profile. enter image description here

Hope this will help future developers in need.

How do I replace all line breaks in a string with <br /> elements?

This will turn all returns into HTML

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

Transparent ARGB hex value

Transparency is controlled by the alpha channel (AA in #AARRGGBB). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.

To get a fully transparent color set the alpha to zero. RR, GG and BB are irrelevant in this case because no color will be visible. This means #00FFFFFF ("transparent White") is the same color as #00F0F8FF ("transparent AliceBlue"). To keep it simple one chooses black (#00000000) or white (#00FFFFFF) if the color does not matter.

In the table you linked to you'll find Transparent defined as #00FFFFFF.

Make a phone call programmatically

Swift 3

let phoneNumber: String = "tel://3124235234"
UIApplication.shared.openURL(URL(string: phoneNumber)!)

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

Is it possible to break a long line to multiple lines in Python?

If you want to assign a long str to variable, you can do it as below:

net_weights_pathname = (
    '/home/acgtyrant/BigDatas/'
    'model_configs/lenet_iter_10000.caffemodel')

Do not add any comma, or you will get a tuple which contains many strs!

How do I make an auto increment integer field in Django?

Edited: Fixed mistake in code that stopped it working if there were no YourModel entries in the db.

There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.

However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).

In your models.py

from django.db import models

def from_500():
    '''
    Returns the next default value for the `ones` field,
    starts from 500
    '''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `ones` field and get the largest entry
    largest = YourModel.objects.all().order_by('ones').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 500
        return 500
    # If an instance of `YourModel` is returned, we get it's
    # `ones` attribute and increment it by 1
    return largest.ones + 1

def add_ten():
    ''' Returns the next default value for the `tens` field'''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `tens` field and get the largest entry
    largest = YourModel.objects.all().order_by('tens').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 10
        return 10
    # If an instance of `YourModel` is returned, we get it's
    # `tens` attribute and increment it by 10
    return largest.tens + 10


class YourModel(model.Model):
    ones = models.IntegerField(primary_key=True,
                               default=from_500)
    tens = models.IntegerField(default=add_ten)

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

strange issue that i solved by comment this line

//$mail->IsSmtp();

whit the last phpmailer version (5.2)

How to center buttons in Twitter Bootstrap 3?

use text-align: center css property

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

AngularJS Error: $injector:unpr Unknown Provider

Since this is the first Stackoverflow question that appears on Google when searching for Error: $injector:unpr Unknown Provider I'll add this here.

Make sure that in your index.html any modules/dependencies are not being loaded after they are needed.

For example in my code customFactory.factory.js begins like this:

angular
   .module("app.module1")
   .factory("customFactory", customFactory);

However the index.html looked like this:

    <script src="/src/client/app/customFactory.factory.js"></script>
    <script src="/src/client/app/module1.module.js"></script>

Where it should've really looked like this:

    <script src="/src/client/app/module1.module.js"></script>
    <script src="/src/client/app/customFactory.factory.js"></script>

Since customFactory.factory.js is declared as part of module1, it needs to be loaded before customFactory

App crashing when trying to use RecyclerView on android 5.0

Since LinearLayoutManager is vertical by default, an easier way to do this is:

recyclerView.setLayoutManager(new LinearLayoutManager(context));

If you want to change the orientation you could use this constructor:

public LinearLayoutManager(Context context, int orientation, boolean reverseLayout);

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

What are the differences between Deferred, Promise and Future in JavaScript?

These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).

Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then. 7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

    Example from CommonJS:

    > asyncComputeTheAnswerToEverything()
        .then(addTwo)
        .then(printResult);
    44
    

     

    Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4

    Always present in popular implementations, and never given resolution abilites. 5 6 7

  • Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9

    However, at least one library uses the term generically for abstracting synchronicity and error handling, while not providing then functionality. 10 It's unclear if avoiding the term 'promise' was intentional, but probably a good choice since promises are built around 'thenables.' 2

References

  1. Wikipedia on Promises & Futures
  2. Promises/A+ spec
  3. DOM Standard on Promises
  4. DOM Standard Promises Spec WIP
  5. DOJO Toolkit Deferreds
  6. jQuery Deferreds
  7. Q
  8. FutureJS
  9. Functional Javascript section on Promises
  10. Futures in AngularJS Integration Testing

Misc potentially confusing things

How to change maven java home

If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME environment variable value for each build. Instead execute Maven like:

JAVA_HOME=/path/to/your/jdk mvn clean install

It will build using the specified JDK, but it won't change your environment variable.

Demo:

$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"

$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"

$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

How to make zsh run as a login shell on Mac OS X (in iTerm)?

chsh -s $(which zsh)

You'll be prompted for your password, but once you update your settings any new iTerm/Terminal sessions you start on that machine will default to zsh.

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

MDN has really nice documentation for all the new ways to import and export modules is ES 6 Import-MDN . A brief description of it in regards to your question you could've either:

  1. Declared the component you were exporting as the 'default' component that this module was exporting: export default class MyNavbar extends React.Component { , and so when Importing your 'MyNavbar' you DON'T have to put curly braces around it : import MyNavbar from './comp/my-navbar.jsx';. Not putting curly braces around an import though is telling the document that this component was declared as an 'export default'. If it wasn't you'll get an error (as you did).

  2. If you didn't want to declare your 'MyNavbar' as a default export when exporting it : export class MyNavbar extends React.Component { , then you would have to wrap your import of 'MyNavbar in curly braces: import {MyNavbar} from './comp/my-navbar.jsx';

I think that since you only had one component in your './comp/my-navbar.jsx' file it's cool to make it the default export. If you'd had more components like MyNavbar1, MyNavbar2, MyNavbar3 then I wouldn't make either or them a default and to import selected components of a module when the module hasn't declared any one thing a default you can use: import {foo, bar} from "my-module"; where foo and bar are multiple members of your module.

Definitely read the MDN doc it has good examples for the syntax. Hopefully this helps with a little more of an explanation for anyone that's looking to toy with ES 6 and component import/exports in React.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

Regular expression that doesn't contain certain string

I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.

<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);

This is the Matcher used:

(?<!EXCEPTION)(\.js)

What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

So you have to exclude conflict dependencies. Try this:

<exclusions>
  <exclusion> 
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </exclusion>
  <exclusion> 
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
  </exclusion>
</exclusions> 

This solved same problem with slf4j and Dozer.

Html.ActionLink as a button or an image, not a link

Just simply :

<button onclick="@Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>

CSS file not refreshing in browser

This sounds like your browser is caching your css. If you are using Firefox, try loading your page using Shift-Reload.

JavaScript - Hide a Div at startup (load)

I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.

How to append text to an existing file in Java?

Sample, using Guava:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

How do I check if a given Python string is a substring of another one?

Try using in like this:

>>> x = 'hello'
>>> y = 'll'
>>> y in x
True

How to Use UTF-8 Collation in SQL Server database?

UTF-8 is not a character set, it's an encoding. The character set for UTF-8 is Unicode. If you want to store Unicode text you use the nvarchar data type.

If the database would use UTF-8 to store text, you would still not get the text out as encoded UTF-8 data, you would get it out as decoded text.

You can easily store UTF-8 encoded text in the database, but then you don't store it as text, you store it as binary data (varbinary).

move div with CSS transition

This may be the good solution for you: change the code like this very little change

.box{
    position: relative; 
}
.box:hover .hidden{
    opacity: 1;
    width:500px;
}
.box .hidden{
    background: yellow;
    height: 334px; 
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    opacity: 0;
    transition: all 1s ease;
}

See demo here

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Regex for not empty and not whitespace

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

How do I download a binary file over HTTP?

if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile

require 'pull_tempfile'

PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
  CSV.foreach(tmp_file.path) do |row|
    # ....
  end
end

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

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

Laravel migration: unique key is too long, even if specified

If anyone else stumbles upon this answer like I did but for a different reason, you may check your Laravel DB charset/collation.

I was installing an application (Snipe-IT) and had configured the Laravel database config to use the following:

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',

Removing mb4 from both strings fixed the issue, although I believe Antonio's answer is the real solution to the problem.

Showing an image from console in Python

If you would like to show it in a new window, you could use Tkinter + PIL library, like so:

import tkinter as tk
from PIL import ImageTk, Image

def show_imge(path):
    image_window = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(image_window, image=img)
    panel.pack(side="bottom", fill="both", expand="yes")
    image_window.mainloop()

This is a modified example that can be found all over the web.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

How to set OnClickListener on a RadioButton in Android?

Since this question isn't specific to Java, I would like to add how you can do it in Kotlin:

radio_group_id.setOnCheckedChangeListener({ radioGroup, optionId -> {
        when (optionId) {
            R.id.radio_button_1 -> {
                // do something when radio button 1 is selected
            }
            // add more cases here to handle other buttons in the RadioGroup
        }
    }
})

Here radio_group_id is the assigned android:id of the concerned RadioGroup. To use it this way you would need to import kotlinx.android.synthetic.main.your_layout_name.* in your activity's Kotlin file. Also note that in case the radioGroup lambda parameter is unused, it can be replaced with _ (an underscore) since Kotlin 1.1.

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

Develop Android app using C#

There are indeed C# compilers for Android available. Even though I prefer developing Android Apps in Java, I can recommend MonoForAndroid. You find more information on http://xamarin.com/monoforandroid

pip: no module named _internal

you can remove it first, and install again ,it will be ok. for centos:

yum remove python-pip
yum install python-pip