Programs & Examples On #Interop

Interoperability is a requirement for one computer system or programming language to work with another.

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

you can create a service and generate excel on server and then allow clients download excel. cos buying excel license for 1000 ppl, it is better to have one license for server.

hope that helps.

How do I properly clean up Excel interop objects?

You need to be aware that Excel is very sensitive to the culture you are running under as well.

You may find that you need to set the culture to EN-US before calling Excel functions. This does not apply to all functions - but some of them.

    CultureInfo en_US = new System.Globalization.CultureInfo("en-US"); 
    System.Threading.Thread.CurrentThread.CurrentCulture = en_US;
    string filePathLocal = _applicationObject.ActiveWorkbook.Path;
    System.Threading.Thread.CurrentThread.CurrentCulture = orgCulture;

This applies even if you are using VSTO.

For details: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369

How can I make SQL case sensitive string comparison on MySQL?

The good news is that if you need to make a case-sensitive query, it is very easy to do:

SELECT *  FROM `table` WHERE BINARY `column` = 'value'

Better way to cast object to int

Use Int32.TryParse as follows.

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

What about using Excel Data Reader (previously hosted here) an open source project on codeplex? Its works really well for me to export data from excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

UPDATE

After some search around, I came across this article: Faster MS Excel Reading using Office Interop Assemblies. The article only uses Office Interop Assemblies to read data from a given Excel Sheet. The source code is of the project is there too. I guess this article can be a starting point on what you trying to achieve. See if that helps

UPDATE 2

The code below takes an excel workbook and reads all values found, for each excel worksheet inside the excel workbook.

private static void TestExcel()
    {
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Range range = null;

        try
        {
            app.Visible = false;
            app.ScreenUpdating = false;
            app.DisplayAlerts = false;

            string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            book = app.Workbooks.Open(@"C:\data.xls", Missing.Value, Missing.Value, Missing.Value
                                              , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                             , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                            , Missing.Value, Missing.Value, Missing.Value);
            foreach (Worksheet sheet in book.Worksheets)
            {

                Console.WriteLine(@"Values for Sheet "+sheet.Index);

                // get a range to work with
                range = sheet.get_Range("A1", Missing.Value);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,]) range.Value2;

                // View the values
                Console.Write("\t");
                Console.WriteLine();
                for (int i = 1; i <= values.GetLength(0); i++)
                {
                    for (int j = 1; j <= values.GetLength(1); j++)
                    {
                        Console.Write("{0}\t", values[i, j]);
                    }
                    Console.WriteLine();
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            range = null;
            if (book != null)
                book.Close(false, Missing.Value, Missing.Value);
            book = null;
            if (app != null)
                app.Quit();
            app = null;
        }
    }

In the above code, values[i, j] is the value that you need to be added to the dataset. i denotes the row, whereas, j denotes the column.

Exception from HRESULT: 0x800A03EC Error

An additional cause for this error. The code sample below returns the error when the datatable (dtTable) has a blank tablename:

  ' Open Excel workbook
  objExcelApp = New Application
  objExcelWorkbook = objExcelApp.Workbooks.Add()
  objExcelSheet = objExcelWorkbook.ActiveSheet
  objExcelSheet.Name = dtTable.TableName

Write Array to Excel Range

In my case, the program queries the database which returns a DataGridView. I then copy that to an array. I get the size of the just created array and then write the array to an Excel spreadsheet. This code outputs over 5000 lines of data in about two seconds.

//private System.Windows.Forms.DataGridView dgvResults;
dgvResults.DataSource = DB.getReport();

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    var dgArray = new object[dgvResults.RowCount, dgvResults.ColumnCount+1];
    foreach (DataGridViewRow i in dgvResults.Rows)
    {
        if (i.IsNewRow) continue;
        foreach (DataGridViewCell j in i.Cells)
        {
            dgArray[j.RowIndex, j.ColumnIndex] = j.Value.ToString();
        }
    }

    Microsoft.Office.Interop.Excel.Range chartRange;

    int rowCount = dgArray.GetLength(0);
    int columnCount = dgArray.GetLength(1);
    chartRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[2, 1]; //I have header info on row 1, so start row 2
    chartRange = chartRange.get_Resize(rowCount, columnCount);
    chartRange.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dgArray);


    oXL.Visible = false;
    oXL.UserControl = false;
    string outputFile = "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

    oWB.SaveAs("c:\\temp\\"+outputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
}
catch (Exception ex)
{
    //...
}

How to call shell commands from Ruby

Given a command like attrib:

require 'open3'

a="attrib"
Open3.popen3(a) do |stdin, stdout, stderr|
  puts stdout.read
end

I've found that while this method isn't as memorable as

system("thecommand")

or

`thecommand`

in backticks, a good thing about this method compared to other methods is backticks don't seem to let me puts the command I run/store the command I want to run in a variable, and system("thecommand") doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.

See "Executing commands in ruby" and Ruby's Open3 documentation.

WPF Datagrid Get Selected Cell Value

When I faced this problem, I approached it like this: I created a DataRowView, grabbed the column index, and then used that in the row's ItemArray

DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();

How to increase Maximum Upload size in cPanel?

php.ini settings should be like given below, if the '=' symbol is not put between the setting and value, it doesn't work

post_max_size = 100M

upload_max_filesize = 100M

How to reload/refresh jQuery dataTable?

i would recommend using the following code.

table.ajax.reload(null, false); 

The reason for this, user paging will not be reset on reload.
Example:

<button id='refresh'> Refresh </button>

<script>
    $(document).ready(function() {

        table = $("#my-datatable").DataTable();
        $("#refresh").on("click", function () { 
         table.ajax.reload(null, false); 
        });

   });
</script>

detail about this can be found at Here

How to show hidden divs on mouseover?

Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:

Copy the whole document and create a .html file you'll be able to figure out on your own from that!

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>The Divs Case</title>
            <style type="text/css">
            * {margin:0px auto;
            padding:0px;}

            .container {width:800px;
            height:600px;
            background:#FFC;
            border:solid #F3F3F3 1px;}

            .div01 {float:right;
            background:#000;
            height:200px;
            width:200px;
            display:none;}

            .div02 {float:right;
            background:#FF0;
            height:150px;
            width:150px;
            display:none;}

            .div03 {float:right;
            background:#FFF;
            height:100px;
            width:100px;
            display:none;}

            div.container:hover div.div01 {display:block;}
            div.container div.div01:hover div.div02  {display:block;}
            div.container div.div01 div.div02:hover div.div03 {display:block;}

            </style>
            </head>
            <body>

            <div class="container">
              <div class="div01">
                <div class="div02">
                    <div class="div03">
                    </div>
                </div>
              </div>

            </div>
            </body>
            </html>

RegEx for matching UK Postcodes

Some of the regexs above are a little restrictive. Note the genuine postcode: "W1K 7AA" would fail given the rule "Position 3 - AEHMNPRTVXY only used" above as "K" would be disallowed.

the regex:

^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$

Seems a little more accurate, see the Wikipedia article entitled 'Postcodes in the United Kingdom'.

Note that this regex requires uppercase only characters.

The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

I believe this error is caused because the local server and live server are running different versions of MySQL. To solve this:

  1. Open the sql file in your text editor
  2. Find and replace all utf8mb4_unicode_520_ci with utf8mb4_unicode_ci
  3. Save and upload to a fresh mySql db

Hope that helpsenter image description here

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Here are available options if it helps anyone for on_delete

CASCADE, DO_NOTHING, PROTECT, SET, SET_DEFAULT, SET_NULL

c++ integer->std::string conversion. Simple function?

Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);

it also provides some safety:

try{
  std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
 ...
}

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

You have to do two things to remove this error.

  1. The @xmlElement mapping in the model
  2. The client side:

    response = resource.type(MediaType.APPLICATION_XML).put(ClientResponse.class, b1); //consume

    or

    response = resource.accept(MediaType.APPLICATION_XML).put(ClientResponse.class, b1); //produce

How do I find out which computer is the domain controller in Windows programmatically?

To retrieve the information when the DomainController exists in a Domain in which your machine doesn't belong, you need something more.

  DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");

  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
  var controller = domain.FindDomainController();

How to get current user who's accessing an ASP.NET application?

The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

Linux shell sort file according to the second column?

FWIW, here is a sort method for showing which processes are using the most virt memory.

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

Multiple variables in a 'with' statement?

In Python 3.1+ you can specify multiple context expressions, and they will be processed as if multiple with statements were nested:

with A() as a, B() as b:
    suite

is equivalent to

with A() as a:
    with B() as b:
        suite

This also means that you can use the alias from the first expression in the second (useful when working with db connections/cursors):

with get_conn() as conn, conn.cursor() as cursor:
    cursor.execute(sql)

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

How to upgrade rubygems

Install rubygems-update

gem install rubygems-update
update_rubygems
gem update --system

run this commands as root or use sudo.

PHPExcel - creating multiple sheets by iteration

You dont need call addSheet() method. After creating sheet, it already add to excel. Here i fixed some codes:

    //First sheet
    $sheet = $objPHPExcel->getActiveSheet();

    //Start adding next sheets
    $i=0;
    while ($i < 10) {

      // Add new sheet
      $objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating

      //Write cells
      $objWorkSheet->setCellValue('A1', 'Hello'.$i)
                   ->setCellValue('B2', 'world!')
                   ->setCellValue('C1', 'Hello')
                   ->setCellValue('D2', 'world!');

      // Rename sheet
      $objWorkSheet->setTitle("$i");

      $i++;
    }

Vue.js dynamic images not working

Here is a shorthand that webpack will use so you don't have to use require.context.

HTML:

<div class="col-lg-2" v-for="pic in pics">
    <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

Vue Method:

getImgUrl(pic) {
    return require('../assets/'+pic)
}

And I find that the first 2 paragraphs in here explain why this works? well.

Please note that it's a good idea to put your pet pictures inside a subdirectory, instead of lobbing it in with all your other image assets. Like so: ./assets/pets/

What is the difference between single-quoted and double-quoted strings in PHP?

' Single quoted

The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.

Example:

echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;

" Double quoted

Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces {} to include variables if you do not want to use concatenation (.) operator) in string.

Example:

echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";

Is there a performance benefit single quote vs double quote in PHP?

Yes. It is slightly faster to use single quotes.

PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there are any variables within the string.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

byte messageDigest[] = algorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
    String hexByte = Integer.toHexString(0xFF & messageDigest[i]);
    int numDigits = 2 - hexByte.length();
    while (numDigits-- > 0) {
        hexString.append('0');
    }
    hexString.append(hexByte);
}

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Fixing a systemd service 203/EXEC failure (no such file or directory)

When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

Best practices for adding .gitignore file for Python projects?

Here are some other files that may be left behind by setuptools:

MANIFEST
*.egg-info

IOException: Too many open files

This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.

https://www.tecmint.com/increase-set-open-file-limits-in-linux/

How do I change the number of open files limit in Linux?

Check if a string is not NULL or EMPTY

if (-not ([string]::IsNullOrEmpty($version)))
{
    $request += "/" + $version
}

You can also use ! as an alternative to -not.

Print a list of all installed node.js modules

for package in `sudo npm -g ls --depth=0 --parseable`; do
    printf "${package##*/}\n";
done

How to pass a JSON array as a parameter in URL

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

Check if xdebug is working

you can run this small php code

<?php
phpinfo();
?>

Copy the whole output page, paste it in this link. Then analyze. It will show if Xdebug is installed or not. And it will give instructions to complete the installation.

Accessing the web page's HTTP Headers in JavaScript

An answer without additional HTTP call

While it's not possible in general to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can't be exposed easily in any other way than via a header:

You may use Server-Timing header to expose arbitrary key-value data, and it will be readable by JavaScript.

(*in supported browsers: Firefox 61, Chrome 65, Edge 79; no Safari yet as of 2021.02; no IE)

Example:

server-timing: key;desc="value"
server-timing: key1;desc="value1"
server-timing: key2;desc="value2"
  • or use its compact version where you expose multiple pieces of data in one header, comma-separated.
server-timing: key1;desc="value1", key2;desc="value2"

Example of how Wikipedia uses this header to expose info about cache hit/miss:

Usage of server-timing response header on Wikipedia

Code example (need to account for lack of browser support in Safari and IE):

if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers
    let navTiming = performance.getEntriesByType('navigation')
    if (navTiming.length > 0) { // still not supported as of Safari 14...
        let serverTiming = navTiming[0].serverTiming
        if (serverTiming && serverTiming.length > 0) {
            for (let i=0; i<serverTiming.length; i++) {
                console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)
            }
        }
    }
}

This logs cache = hit-front in supported browsers.

Notes:

  • as mentioned on MDN, the API is only supported over HTTPS
  • if your JS is served from another domain, you have to add Timing-Allow-Origin response header to make the data readable to JS (Timing-Allow-Origin: * or Timing-Allow-Origin: https://www.example.com)
  • Server-Timing headers support also dur(header) field, readable as duration on JS side, but it's optional and defaults to 0 in JS if not passed
  • regarding Safari support: see bug 1 and bug 2
  • You can read more on server-timing in this blog post
  • Note that performance entries buffers might get cleaned by JS on the page (via an API call), or by the browser, if the page issues too many calls for subresources. For that reason, you should capture the data as soon as possible, and/or use PerformanceObserver API instead. See the blog post for details.

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

From the shell if you want to show all results you could do db.collection.find().toArray() to get all results without it.

Why do I get the "Unhandled exception type IOException"?

You should add "throws IOException" to your main method:

public static void main(String[] args) throws IOException {

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

August 2019

In my case I wanted to use a Swift protocol in an Objective-C header file that comes from the same target and for this I needed to use a forward declaration of the Swift protocol to reference it in the Objective-C interface. The same should be valid for using a Swift class in an Objective-C header file. To use forward declaration see the following example from the docs at Include Swift Classes in Objective-C Headers Using Forward Declarations:

// MyObjcClass.h
@class MySwiftClass; // class forward declaration
@protocol MySwiftProtocol; // protocol forward declaration

@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftClassInstance;
- (id <MySwiftProtocol>)returnInstanceAdoptingSwiftProtocol;
// ...
@end

Easiest way to use SVG in Android?

Rather than adding libraries which increases your apk size, I will suggest you to convert Svg to drawable using http://inloop.github.io/svg2android/ . and add vectorDrawables.useSupportLibrary = true in gradle,

Return multiple values from a function in swift

//By : Dhaval Nimavat
    import UIKit

   func weather_diff(country1:String,temp1:Double,country2:String,temp2:Double)->(c1:String,c2:String,diff:Double)
   {
    let c1 = country1
    let c2 = country2
    let diff = temp1 - temp2
    return(c1,c2,diff)
   }

   let result = 
   weather_diff(country1: "India", temp1: 45.5, country2: "Canada", temp2:    18.5)
   print("Weather difference between \(result.c1) and \(result.c2) is \(result.diff)")

How can I have Github on my own server?

You have a lot of options to run your own git server,

  1. Bitbucket Server

    Bitbucket Server is not free, but not costly. It costs you one time only(10$ as of now). Bitbucket is a nice option if you want a long-lasting solution.

  2. Gitea (https://gitea.io/en-us/)

    Gitea it's an open-source project. It's cross-platform and lightweight. You can use it without any cost. originally forked from Gogs(http://gogs.io). It is lightweight code hosting solution written in Golang and released under the MIT license. It works on Windows, macOS, Linux, ARM and more.

  3. Gogs (http://gogs.io)

    Gogs is a self-hosted and open source project having around 32k stars on github. You can set up the Gogs at no cost.

  4. GitLab (https://gitlab.com/)

    GitLab is a free, open-source and a web-based Git-repository manager software. It has a wiki, issue tracking, and other features. The code was originally written in Ruby, with some parts later rewritten in Golang. GitLab Community Edition (CE) is an open-source end-to-end software development platform with built-in version control, issue tracking, code review, CI/CD, and more. Self-host GitLab CE on your own servers, in a container, or on a cloud provider.

  5. GNU Savannah (https://savannah.gnu.org/)

    GNU Savannah is free and open-source software from the Free Software Foundation. It currently offers CVS, GNU arch, Subversion, Git, Mercurial, Bazaar, mailing list, web hosting, file hosting, and bug tracking services. However, this software is not for new users. It takes a little time to setup and masters everything about it.

  6. GitPrep (http://gitprep.yukikimoto.com/)

    GitPrep is Github clone. you can install portable GitHub system into UNIX/Linux. You can create users and repositories without limitation. This is free software.

  7. Kallithes (https://kallithea-scm.org/)

    Kallithea, a member project of Software Freedom Conservancy, is a GPLv3'd, Free Software source code management system that supports two leading version control systems, Mercurial and Git, and has a web interface that is easy to use for users and admins. You can install Kallithea on your own server and host repositories for the version control system of your choice.

  8. Tuleap (https://www.tuleap.org/)

    Tuleap is a Software development & agile management All-in-one, 100% Open Source. You can install it on docker or CentOS server.

  9. Phacility (https://www.phacility.com/)

    Phabricator is open source and you can download and install it locally on your own hardware for free. The open source install is a complete install with the full featureset.

How can I read large text files in Python, line by line, without loading it into memory?

The best solution I found regarding this, and I tried it on 330 MB file.

lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
    file.seek(lineno * (line_length + 2))
    print(file.readline(), end='')

Where line_length is the number of characters in a single line. For example "abcd" has line length 4.

I have added 2 in line length to skip the '\n' character and move to the next character.

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Java: Clear the console

You need to use JNI.

First of all use create a .dll using visual studio, that call system("cls"). After that use JNI to use this DDL.

I found this article that is nice:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

Logging POST data from $request_body

The solution below was the best format I found.

log_format postdata escape=json '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$request_body"';
server {
        listen 80;

        server_name api.some.com;

        location / {
         access_log  /var/log/nginx/postdata.log  postdata;
         proxy_pass      http://127.0.0.1:8080;
        }

}

For this input

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://api.deprod.com/postEndpoint

Generate that great result

201.23.89.149 -  [22/Aug/2019:15:58:40 +0000] "POST /postEndpoint HTTP/1.1" 200 265 "" "curl/7.64.0" "{\"key1\":\"value1\", \"key2\":\"value2\"}"

Android Completely transparent Status Bar?

The following code will make your status bar along with the navigation bar transparent (note that this will make your layout a full screen layout like the layouts used in games):

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables sticky immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE_STICKY.
    // Or for regular immersive mode replace it with SYSTEM_UI_FLAG_IMMERSIVE
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

To learn more, visit this link.

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

The excellent JavaScript library KeyboardJS handles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.

KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });

If you want a simple version, head to the answer by @tonycoupland):

var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

What do >> and << mean in Python?

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

How can I add 1 day to current date?

Inspired by jpmottin in this question, here's the one line code:

_x000D_
_x000D_
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
_x000D_
_x000D_

Hope this helps

git ignore exception

Since Git 2.7.0 Git will take exceptions into account. From the official release notes:

  • Allow a later "!/abc/def" to override an earlier "/abc" that appears in the same .gitignore file to make it easier to express "everything in /abc directory is ignored, except for ...".

https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.7.0.txt

edit: apparently this doesn't work any more since Git 2.8.0

How to create a folder with name as current date in batch (.bat) files

If your locale has date format "DDMMYYYY" you'll have to set it this way:

set datestr=%date:~-4,4%%date:~3,2%%date:~-10,2%
mkdir %datestr%

mysql stored-procedure: out parameter

SET out_number=SQRT(input_number); 

Instead of this write:

select SQRT(input_number); 

Please don't write SET out_number and your input parameter should be:

PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT) 

SQL Server: Database stuck in "Restoring" state

By default, every RESTORE DATABASE comes with RECOVERY set up. The 'NORECOVERY' options, basically tells the SQL Server that the database is waiting for more restore files (could be a DIFF file and LOG file and, could include tail-log backup file, if possible). The 'RECOVERY' options, finish all transactions and let the database ready to perform transactions.

So:

  1. if your database is set up with SIMPLE recovery model, you can only perform a FULL restore with NORECOVERY option, when you have a DIFF backup. No LOG backup are allowed in SIMPLE recovery model database.
  2. Otherwise, if your database is set up with FULL or BULK-LOGGED recovery model, you can perform a FULL restore followed by NORECOVERYoption, then perform a DIFF followed by NORECOVERY, and, at last, perform LOG restore with RECOVERY option.

Remember, THE LAST RESTORE QUERY MUST HAVE RECOVERY OPTION. It could be an explicit way or not. In therms of T-SQL, the situation:

1.

 USE [master]
    GO
    RESTORE DATABASE Database_name 
    FROM DISK = N'\\path_of_backup_file.bak WITH FILE = 1, [REPLACE],NOUNLOAD, 
    RECOVERY -- This option could be omitted.
    GO

WITH REPLACE option must be used with caution as it can lead to data loss

Or, if you perform a FULL and DIFF backup, you can use this

   USE [master]
    GO
    RESTORE DATABASE Database_name
      FROM DISK = N'\\path_of_backup_file.bak' WITH FILE = 1, 
       NOUNLOAD,NORECOVERY
    GO
    RESTORE DATABASE Database_name
      FROM DISK =N'\\path_of_**diff**backup_file.bak' WITH FILE = 1, 
     NOUNLOAD, RECOVERY
    GO

 2. USE [master]
    GO
   -- Perform a Tail-Log backup, if possible. 
   BACKUP LOG Database_name
   GO
   -- Restoring a FULL backup
   RESTORE DATABASE Database_name
    FROM DISK = N'\\path_of_backup_file.bak' WITH FILE = 1, 
     NOUNLOAD,NORECOVERY
  GO 
  -- Restore the last DIFF backup
  RESTORE DATABASE Database_name
    FROM DISK = N'\\path_of_DIFF_backup_file.bak' WITH FILE = 1,
     NORECOVERY,NOUNLOAD
  GO
  -- Restore a Log backup
  RESTORE LOG Database_name
    FROM DISK = N'path_of_LOG_backup_file.trn' WITH FILE = 2,
    RECOVERY, NOUNLOAD
  GO

Of course, you can perform a restore with the option STATS = 10 that tells the SQL Server to report every 10% completed.

If you prefer, you can observe the process or restore in real-time based query. As follow:

USE[master]
GO
SELECT session_id AS SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time 
    FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a 
        WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')
GO

Hope this help.

Deep copy vs Shallow Copy

Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.

What type of a copy does a copy constructor does?

It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.

Foreign Key naming scheme

The standard convention in SQL Server is:

FK_ForeignKeyTable_PrimaryKeyTable

So, for example, the key between notes and tasks would be:

FK_note_task

And the key between tasks and users would be:

FK_task_user

This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:

FK_task_user
FK_note_task
FK_note_user

So you can see that tasks depend on users, and notes depend on both tasks and users.

Specify a Root Path of your HTML directory for script links?

/ means the root of the current drive;

./ means the current directory;

../ means the parent of the current directory.

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

How to get query string parameter from MVC Razor markup?

Similar thread

<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

EDIT 01-10-2014: Since this question is so popular this answer has been improved.

The example above will only get the values from RouteData, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:

<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

You can also check RouteValues vs QueryString MVC?

EDIT 03-05-2019: Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query object from Context.Request path. So it would be:

<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>

Please notice I am using StringValues("1") in the statement because Query returns StringValues struct instead of pure string. That's cleanes way for this scenerio which I've found.

Why is processing a sorted array faster than processing an unsorted array?

This question is rooted in branch prediction models on CPUs. I'd recommend reading this paper:

Increasing the Instruction Fetch Rate via Multiple Branch Prediction and a Branch Address Cache

When you have sorted elements, the IR can not be bothered to fetch all CPU instructions, again and again. It fetches them from the cache.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows:

  • Ctrl+K,Ctrl+U for UPPERCASE.
  • Ctrl+K,Ctrl+L for lowercase.

Method 1 (Two keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K, release K while holding Ctrl. (Do not release the Ctrl key)
  3. Immediately, press U (for uppercase) OR L (for lowercase) with Ctrl still being pressed, then release all pressed keys.

Method 2 (3 keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K.
  3. Without releasing Ctrl and K, immediately press U (for uppercase) OR L (for lowercase) and release all pressed keys.

Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.

I use the above shortcuts, and they work on my Windows system.

Subdomain on different host

sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g

mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain

anothersite.mydomain.com

of which the site is actually on another server then

login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11

And that's it.

iOS: set font size of UILabel Programmatically

For iOS 8

  static NSString *_myCustomFontName;

 + (NSString *)myCustomFontName:(NSString*)fontName
  {
 if ( !_myCustomFontName )
  {
   NSArray *arr = [UIFont fontNamesForFamilyName:fontName];
    // I know I only have one font in this family
    if ( [arr count] > 0 )
       _myCustomFontName = arr[0];
  }

 return _myCustomFontName;

 }

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

Date only from TextBoxFor()

Keep in mind that display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.

If you wish to force the format escape / in the following manner:

@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")

If not escaped for me it show 08-01-2010 vs. expected 08/01/2010.

Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012.

How do I get countifs to select all non-blank cells in Excel?

In Excel 2010, You have the countifS function.

I was having issues if I was trying to count the number of cells in a range that have a non0 value.

e.g. If you had a worksheet that in the range A1:A10 had values 1, 0, 2, 3, 0 and you wanted the answer 3.

The normal function =COUNTIF(A1:A10,"<>0") would give you 8 as it is counting the blank cells as 0s.

My solution to this is to use the COUNTIFS function with the same range but multiple criteria e.g.

=COUNTIFS(A1:A10,"<>0",A1:A10,"<>")

This effectively checks if the range is non 0 and is non blank.

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

All you need to do is install the platform for the desired emulator example for android 11

sdkmanager --install "platforms;android30"

after you do this your emulator will start working just fine.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

On Windows (msys) using Docker Toolbox/Machine, I had to add an extra / before /bin/bash to indicate that it was a *nix filepath.

So, docker run --rm -it <image>:latest //bin/bash

flutter remove back button on appbar

Use this for slivers AppBar

SliverAppBar (
        automaticallyImplyLeading: false,
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        pinned: true,
      ),

Use this for normal Appbar

 appBar: AppBar(
    title: Text
    ("You decide on the appbar name"
    style: TextStyle(color: Colors.black,), 
    elevation: 0,
    brightness: Brightness.light,
    backgroundColor: Colors.white,
    automaticallyImplyLeading: false,

),

Return an empty Observable

You can return Observable.of(empty_variable), for example

Observable.of('');

// or
Observable.of({});

// etc

How to pass optional parameters while omitting some other optional parameters?

Another approach is:

error(message: string, options?: {title?: string, autoHideAfter?: number});

So when you want to omit the title parameter, just send the data like that:

error('the message', { autoHideAfter: 1 })

I'd rather this options because allows me to add more parameter without having to send the others.

Case Insensitive String comp in C

I've found built-in such method named from which contains additional string functions to the standard header .

Here's the relevant signatures :

int  strcasecmp(const char *, const char *);
int  strncasecmp(const char *, const char *, size_t);

I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.

tolower(unsigned char ch) {
    if (ch >= 'A' && ch <= 'Z')
        ch = 'a' + (ch - 'A');
    return ch;
 }

int strcasecmp(const char *s1, const char *s2) {
    const unsigned char *us1 = (const u_char *)s1,
                        *us2 = (const u_char *)s2;

    while (tolower(*us1) == tolower(*us2++))
        if (*us1++ == '\0')
            return (0);
    return (tolower(*us1) - tolower(*--us2));
}

How to list processes attached to a shared memory segment in linux?

Just in case someone is interest only in what kind of process created the shared moeries, call

ls -l /dev/shm

It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.

Find column whose name contains a specific string

Getting name and subsetting based on Start, Contains, and Ends:

# from: https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html




import pandas as pd



data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)



print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist() 
print("Contains")
print(colNames_contains)



print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist() 
print("Starts")
print(colNames_starts)



print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist() 
print("Ends")
print(colNames_ends)



print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)



print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)



print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)

Why does .NET foreach loop throw NullRefException when collection is null?

Because behind the scenes the foreach acquires an enumerator, equivalent to this:

using (IEnumerator<int> enumerator = returnArray.getEnumerator()) {
    while (enumerator.MoveNext()) {
        int i = enumerator.Current;
        // do some more stuff
    }
}

How to check for an undefined or null variable in JavaScript?

You can just check if the variable has a value or not. Meaning,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

Using :before CSS pseudo element to add image to modal

http://caniuse.com/#search=::after

::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Is this what you're looking for?

.Modal::after{
  content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
  position:relative; /*or absolute*/
  z-index:100000; /*a number that's more than the modal box*/
  left:-50px;
  top:10px;
}

.ModalCarrot{
   position:absolute;
   left:50%;
   margin-left:-8px;
   top:-16px;
}

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The correct solution seems to be:

<Window.Resources>
    <CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
    <DataGridComboBoxColumn Header="Column With Predefined Values"
                            ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
                            SelectedValueBinding="{Binding MyItemId}"
                            SelectedValuePath="Id"
                            DisplayMemberPath="StatusCode" />
</DataGrid>

The layout above works perfectly fine for me, and should work for others. This design choice also makes sense, though it isn't very well explained anywhere. But if you have a data column with predefined values, those values typically don't change during run-time. So creating a CollectionViewSource and initializing the data once makes sense. It also gets rid of the longer bindings to find an ancestor and bind on it's data context (which always felt wrong to me).

I am leaving this here for anyone else who struggled with this binding, and wondered if there was a better way (As this page is obviously still coming up in search results, that's how I got here).

Redirect to external URL with return in laravel

Define the url you want to redirect in $url

Then just use

return Redirect::away($url);

If you want to redirect inside your views use

return Redirect::to($url);

Read more about Redirect here

Update 1 :

Here is the simple example

return Redirect::to('http://www.google.com');

Update 2 :

As the Questioner wants to return in the same page

$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;

How to use comparison operators like >, =, < on BigDecimal

This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

  • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
  • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

SQL statement to get column type

USE [YourDatabaseName]
GO

SELECT column_name 'Column Name',
data_type 'Data Type'
FROM information_schema.columns
WHERE table_name = 'YourTableName'
GO

This will return the values Column Name, showing you the names of the columns, and the Data Types of those columns (ints, varchars, etc).

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

How to insert a new line in strings in Android

Try:

String str = "my string \n my other string";

When printed you will get:

my string
my other string

SQL Server - after insert trigger - update another column in the same table

Yes, it will recursively call your trigger unless you turn the recursive triggers setting off:

ALTER DATABASE db_name SET RECURSIVE_TRIGGERS OFF 

MSDN has a good explanation of the behavior at http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx under the Recursive Triggers heading.

Alter column, add default constraint

alter table TableName drop constraint DF_TableName_WhenEntered

alter table TableName add constraint DF_TableName_WhenEntered default getutcdate() for WhenEntered

What do the crossed style properties in Google Chrome devtools mean?

On a side note. If you are using @media queries (such as @media screen (max-width:500px)) pay particular attention to applying @media query AFTER you are done with normal styles. Because @media query will be crossed out (even though it is more specific) if followed by css that manipulates the same elements. Example:

@media (max-width:750px){
#buy-box {width: 300px;}
}

#buy-box{
width:500px;
}

** width will be 500px and 300px will be crossed out in Developer Tools. **

#buy-box{
width:500px;
}

@media (max-width:750px){
#buy-box {width: 300px;}
}

** width will be 300px and 500px will be crossed out **

How to call stopservice() method of Service class from the calling activity class

That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

AutoService

class AutoService extends IntentService {
     private static final String TAG = "AutoService";
     private Timer timer;    
     private TimerTask task;

     public onCreate() {
          timer = new Timer();
          timer = new TimerTask() {
            public void run() 
            {
                System.out.println("done");
            }
          }
     }

     protected void onHandleIntent(Intent i) {
        Log.d(TAG, "onHandleIntent");     

        int delay = 5000; // delay for 5 sec.
        int period = 5000; // repeat every sec.


        timer.scheduleAtFixedRate(timerTask, delay, period);
     }

     public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        timer.cancel();
        task.cancel();
        return super.stopService(name);
    }

}

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

creating Hashmap from a JSON String

You could use Jackson to do this. I have yet to find a simple Gson solution.

Where data_map.json is a JSON (object) resource file
and data_list.json is a JSON (array) resource file.

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Based on:
 * 
 * http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
 */
public class JsonLoader {
    private static final ObjectMapper OBJ_MAPPER;
    private static final TypeReference<Map<String,Object>> OBJ_MAP;
    private static final TypeReference<List<Map<String,Object>>> OBJ_LIST;

    static {
        OBJ_MAPPER = new ObjectMapper();
        OBJ_MAP = new TypeReference<Map<String,Object>>(){};
        OBJ_LIST = new TypeReference<List<Map<String,Object>>>(){};
    }

    public static void main(String[] args) {
        try {
            System.out.println(jsonToString(parseJsonString(read("data_map.json", true))));
            System.out.println(jsonToString(parseJsonString(read("data_array.json", true))));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final Object parseJsonString(String jsonString) {
        try {
            if (jsonString.startsWith("{")) {
                return readJsonObject(jsonString);
            } else if (jsonString.startsWith("[")) {
                return readJsonArray(jsonString);
            }
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String jsonToString(Object json) throws JsonProcessingException {
        return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
    }

    private static final Map<String,Object> readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException {
        return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP);
    }

    private static final List<Map<String,Object>> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException {
        return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST);
    }

    public static final Map<String,Object> loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
        return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP);
    }

    public static final List<Map<String,Object>> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
        return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST);
    }

    private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return JsonLoader.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }

    protected static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    protected static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    public static String read(String path, boolean isResource) throws IOException {
        return read(path, "UTF-8", isResource);
    }

    public static String read(String path, String charset, boolean isResource) throws IOException {
        return read(pathToUrl(path, isResource), charset);
    }

    @SuppressWarnings("resource")
    public static String read(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }
}

Extra

Here is the complete code for Dheeraj Sachan's example.

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

public class JsonHandler {
    private static ObjectMapper propertyMapper;

    static {
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        propertyMapper = new ObjectMapper();
        propertyMapper.setDateFormat(df);
        propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    }

    private static class MyHashMap extends HashMap<String, List<Video>>{
        private static final long serialVersionUID = 7023107716981734468L;
    }

    private static class Video implements Serializable {
        private static final long serialVersionUID = -446275421030765463L;

        private String dashUrl;
        private String videoBitrate;
        private String audioBitrate;
        private int videoWidth;
        private int videoHeight;
        private long fileSize;

        @Override
        public String toString() {
            return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate
                    + ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]";
        }
    }

    public static void main(String[] args) {
        try {
            HashMap<String, List<Video>> map = loadJson("sample.json", true);
            Iterator<Entry<String, List<Video>>> lectures = map.entrySet().iterator();

            while (lectures.hasNext()) {
                Entry<String, List<Video>> lecture = lectures.next();

                System.out.printf("Lecture #%s%n", lecture.getKey());

                for (Video video : lecture.getValue()) {
                    System.out.println(video);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
        try {
            if (json == null) {
                return null;
            }
            return propertyMapper.readValue(json, classOfT);

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return JsonHandler.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }

    public static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    public static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    @SuppressWarnings("resource")
    public static String readFile(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }

    public static String loadJsonString(String path, boolean isResource) throws IOException {
        return readFile(path, isResource, "UTF-8");
    }

    public static String readFile(String path, boolean isResource, String charset) throws IOException {
        return readFile(pathToUrl(path, isResource), charset);
    }

    public static HashMap<String, List<Video>> loadJson(String jsonString) throws IOException {
        return JsonHandler.parseUnderScoredResponse(jsonString, MyHashMap.class);
    }

    public static HashMap<String, List<Video>> loadJson(String path, boolean isResource) throws IOException {
        return loadJson(loadJsonString(path, isResource));
    }
}

How to use npm with node.exe?

Here is a guide by @CTS_AE on how to use NPM with standalone node.exe: https://stackoverflow.com/a/31148216/228508

  1. Download the node.exe stand-alone from nodejs.org
  2. Grab an NPM release zip off of github https://github.com/npm/npm/releases
  3. Create a folder named: node_modules in the same folder as node.exe
  4. Extract the NPM zip into the node_modules folder
  5. Rename the extracted npm folder to npm and remove any versioning ie: npm-3.3.4 –> npm.
  6. Copy npm.cmd out of the /npm/bin/ folder into the root folder with node.exe

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

I solved the problem by changing

$db['default']['pconnect'] = TRUE; TO $db['default']['pconnect'] = FALSE;

in /application/config/database.php

Setting the number of map tasks and reduce tasks

As Praveen mentions above, when using the basic FileInputFormat classes is just the number of input splits that constitute the data. The number of reducers is controlled by mapred.reduce.tasks specified in the way you have it: -D mapred.reduce.tasks=10 would specify 10 reducers. Note that the space after -D is required; if you omit the space, the configuration property is passed along to the relevant JVM, not to Hadoop.

Are you specifying 0 because there is no reduce work to do? In that case, if you're having trouble with the run-time parameter, you can also set the value directly in code. Given a JobConf instance job, call

job.setNumReduceTasks(0);

inside, say, your implementation of Tool.run. That should produce output directly from the mappers. If your job actually produces no output whatsoever (because you're using the framework just for side-effects like network calls or image processing, or if the results are entirely accounted for in Counter values), you can disable output by also calling

job.setOutputFormat(NullOutputFormat.class);

Simple Java Client/Server Program

There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a "Public IP Address". "www.whatismyipaddress.com" will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that's why IPv4 is still in effect) I guess you're trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.

What is the best way to parse html in C#?

I've used ZetaHtmlTidy in the past to load random websites and then hit against various parts of the content with xpath (eg /html/body//p[@class='textblock']). It worked well but there were some exceptional sites that it had problems with, so I don't know if it's the absolute best solution.

ImportError: No module named matplotlib.pyplot

I had a similar issue that I resolved and here is my issue:

I set everything up on python3 but I was using python to call my file for example: I was typing "python mnist.py" ...since I have everything on python3 it was thinking I was trying to use python 2.7

The correction: "python3 mnist.py" - the 3 made all the difference

I'm by no means an expert in python or pip, but there is definitely a difference between pip and pip3 (pip is tied to python 2.7) (pip3 is tied to python 3.6)

so when installing for 2.7 do: pip install when installing for 3.6 do: pip3 install

and when running your code for 2.7 do: python when running your code for 3.6 do: python3

I hope this helps someone!

Eliminating NAs from a ggplot

You can use the function subset inside ggplot2. Try this

library(ggplot2)

data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example

ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) + 
geom_bar(stat="bin")

What is the best (idiomatic) way to check the type of a Python variable?

type(dict()) says "make a new dict, and then find out what its type is". It's quicker to say just dict. But if you want to just check type, a more idiomatic way is isinstance(x, dict).

Note, that isinstance also includes subclasses (thanks Dustin):

class D(dict):
    pass

d = D()
print("type(d) is dict", type(d) is dict)  # -> False
print("isinstance (d, dict)", isinstance(d, dict))  # -> True

Appropriate datatype for holding percent values?

If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.

EDIT: The decimal type is probably a better match. Then you don't need to manually scale. It takes 5 bytes per value.

Prevent redirect after form is submitted

You should post it with ajax, this will stop it from changing the page, and you will still get the information back.

$(function() {
    $('form').submit(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: { username: $(this).name.value, 
                    password: $(this).password.value }
        });
        return false;
    }); 
})

See Post documentation for JQuery

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I was getting this error message when trying to close the dialog by using a button inside the dialog body. I tried to use $('#myDialog').dialog('close'); which did not work.

I ended up firing the click action of the 'x' button on the header using:

$('.modal-header:first').find('button:first').click();  

Select Multiple Fields from List in Linq

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  <style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
     }
    });

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

return isFormValid;
}   
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>

Clearing a text field on button click

Something like this will add a button and let you use it to clear the values

<div>           
<input type="text" id="textfield1" size="5"/>         
</div>

<div>          
<input type="text" id="textfield2" size="5"/>           
</div>

<div>
    <input type="button" onclick="clearFields()" value="Clear">
</div>


<script type="text/javascript">
function clearFields() {
    document.getElementById("textfield1").value=""
    document.getElementById("textfield2").value=""
}
</script>

How to Call Controller Actions using JQuery in ASP.NET MVC

In response to the above post I think it needs this line instead of your line:-

var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' &param2='+value2

Or else you send the actual strings value1 and value2 to the controller.

However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.


Here is a working solution. For the cshtml page:-

   <button type="button" onclick="ButtonClick();"> Call &raquo;</button>

<script>
    function ButtonClick()
    {
        callControllerMethod2("1", "2");
    }
    function callControllerMethod2(value1, value2)
    {
        var response = null;
        $.ajax({
            async: true,
            url: "Logging/SubMenu_Click?param1=" + value1 + " &param2=" + value2,
            cache: false,
            dataType: "json",
            success: function (data) { receiveResponse(data); }
        });
    }
    function receiveResponse(response)
    {
        if (response != null)
        {
            for (var i = 0; i < response.length; i++)
            {
                alert(response[i].Data);
            }
        }
    }
</script>

And for the controller:-

public class A
{
    public string Id { get; set; }
    public string Data { get; set; }

}
public JsonResult SubMenu_Click(string param1, string param2)
{
    A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
    return Json(arr , JsonRequestBehavior.AllowGet);
}

You can see the time changing each time it is called, so there is no caching of the values...

Reading an Excel file in PHP

// Here is the simple code using COM object in PHP
class Excel_ReadWrite{

    private $XLSHandle;
    private $WrkBksHandle;
    private $xlBook;

    function __construct() {
        $this->XLSHandle = new COM("excel.application") or die("ERROR: Unable to instantaniate COM!\r\n"); 
    }

    function __destruct(){
        //if already existing file is opened
        if($this->WrkBksHandle != null)
        {   
            $this->WrkBksHandle->Close(True);
            unset($this->WrkBksHandle);
            $this->XLSHandle->Workbooks->Close();
        }
        //if created new xls file
        if($this->xlBook != null)
        {
            $this->xlBook->Close(True);
            unset($this->xlBook);
        }
        //Quit Excel Application
        $this->XLSHandle->Quit();
        unset($this->XLSHandle);
    }

    public function OpenFile($FilePath)
    {
        $this->WrkBksHandle = $this->XLSHandle->Workbooks->Open($FilePath);
    }

    public function ReadData($RowNo, $ClmNo)
    {
       $Value = $this->XLSHandle->ActiveSheet->Cells($RowNo, $ClmNo)->Value;
       return $Value;
    }  

    public function SaveOpenedFile()
    {
        $this->WrkBksHandle->Save(); 
    }  

    /***********************************************************************************
    * Function Name:- WriteToXlsFile() will write data based on row and column numbers
    * @Param:- $CellData- cell data
    * @Param:- $RowNumber- xlsx file row number
    * @Param:- $ColumnNumber- xlsx file column numbers
   ************************************************************************************/
   function WriteToXlsFile($CellData, $RowNumber, $ColumnNumber)
   {
       try{
               $this->XLSHandle->ActiveSheet->Cells($RowNumber,$ColumnNumber)->Value = $CellData;
           }
       catch(Exception $e){
               throw new Exception("Error:- Unable to write data to xlsx sheet");
           }
   }


   /****************************************************************************************
    * Function Name:- CreateXlsFileWithClmName() will initialize xls file with column Names
    * @Param:- $XlsColumnNames- Array of columns data
    * @Param:- $XlsColumnWidth- Array of columns width
   *******************************************************************************************/
   function CreateXlsFileWithClmNameAndWidth($WorkSheetName = "Raman", $XlsColumnNames = null, $XlsColumnWidth = null)
   {
       //Hide MS Excel application window
       $this->XLSHandle->Visible = 0;
       //Create new document
       $this->xlBook = $this->XLSHandle->Workbooks->Add();

       //Create Sheet 1
       $this->xlBook->Worksheets(1)->Name = $WorkSheetName;
       $this->xlBook->Worksheets(1)->Select;

       if($XlsColumnWidth != null)
       {
           //$XlsColumnWidth = array("A1"=>15,"B1"=>20);
           foreach($XlsColumnWidth as $Clm=>$Width)
           {
               //Set Columns Width
               $this->XLSHandle->ActiveSheet->Range($Clm.":".$Clm)->ColumnWidth = $Width;
           }    
       }
       if($XlsColumnNames != null)
       {
           //$XlsColumnNames = array("FirstColumnName"=>1, "SecondColumnName"=>2);
           foreach($XlsColumnNames as $ClmName=>$ClmNumber)
           {
               // Cells(Row,Column)
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Value = $ClmName;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Font->Bold = True;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Interior->ColorIndex = "15";
           }
       }
   }
   //56 is for xls 8
    public function SaveCreatedFile($FileName, $FileFormat = 56)
    {
        $this->xlBook->SaveAs($FileName, $FileFormat);
    }

    public function MakeFileVisible()
    {
       //Hide MS Excel application window`enter code here`
       $this->XLSHandle->Visible = 1;
    }
}//end of EXCEL class

Using group by on two fields and count in SQL

You must group both columns, group and sub-group, then use the aggregate function COUNT().

SELECT
  group, subgroup, COUNT(*)
FROM
  groups
GROUP BY
  group, subgroup

How to exit in Node.js

The exit in node js is done in two ways:

  • Calling process.exit() explicitly.
  • Or, if nodejs event loop is done with all tasks, and there is nothing left to do. Then, the node application will automatically exit.

How it works?

If you want to force the execution loop to stop the process, yo can use the global variable process which is an instance of EventEmitter. So when you call process.exit() you actually emit the exit event that ends all tasks immediately even if there still are asynchronous operations not been done.

process.exit() takes an exit code (Integer) as a parameter. The code 0 is the default and this means it exit with a 'success'. While the code 1 means it exit with a 'failure'.

jquery input select all on focus

There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )

This fiddle fixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:

Tested in IE > 8

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

How to debug Lock wait timeout exceeded on MySQL?

Due to the popularity of MySQL, there's no wonder Lock wait timeout exceeded; try restarting transaction exception gets so much attention on SO.

The more contention you have, the greater the chance of deadlocks, which a DB engine will resolve by time-outing one of the deadlocked transactions.

Also, long-running transactions that have modified (e.g. UPDATE or DELETE) a large number of entries are more likely to generate conflicts with other transactions.

Although InnoDB MVCC, you can still request explicit locks using the FOR UPDATE clause. However, unlike other popular DBs (Oracle, MSSQL, PostgreSQL, DB2), MySQL uses REPEATABLE_READ as the default isolation level.

Now, the locks that you acquired (either by modifying rows or using explicit locking), are held for the duration of the currently running transaction. If you want a good explanation of the difference between REPEATABLE_READ and READ COMMITTED in regards to locking, please read this Percona article.

In REPEATABLE READ every lock acquired during a transaction is held for the duration of the transaction.

In READ COMMITTED the locks that did not match the scan are released after the STATEMENT completes.

...

This means that in READ COMMITTED other transactions are free to update rows that they would not have been able to update (in REPEATABLE READ) once the UPDATE statement completes.

Therefore: The more restrictive the isolation level (REPEATABLE_READ, SERIALIZABLE) the greater the chance of deadlock. This is not an issue "per se", it's a trade-off.

You can get very good results with READ_COMMITED, as you need application-level lost update prevention when using logical transactions that span over multiple HTTP requests. The optimistic locking approach targets lost updates that might happen even if you use the SERIALIZABLE isolation level while reducing the lock contention by allowing you to use READ_COMMITED.

Creating layout constraints programmatically

Hi I have been using this page a lot for constraints and "how to". It took me forever to get to the point of realizing I needed:

myView.translatesAutoresizingMaskIntoConstraints = NO;

to get this example to work. Thank you Userxxx, Rob M. and especially larsacus for the explanation and code here, it has been invaluable.

Here is the code in full to get the examples above to run:

UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor redColor];
myView.translatesAutoresizingMaskIntoConstraints = NO;  //This part hung me up 
[self.view addSubview:myView];
//needed to make smaller for iPhone 4 dev here, so >=200 instead of 748
[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"V:|-[myView(>=200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"H:[myView(==200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

Non-recursive depth first search algorithm

You would use a stack that holds the nodes that were not visited yet:

stack.push(root)
while !stack.isEmpty() do
    node = stack.pop()
    for each node.childNodes do
        stack.push(stack)
    endfor
    // …
endwhile

Specifying Style and Weight for Google Fonts

They use regular CSS.

Just use your regular font family like this:

font-family: 'Open Sans', sans-serif;

Now you decide what "weight" the font should have by adding

for semi-bold

font-weight:600;

for bold (700)

font-weight:bold;

for extra bold (800)

font-weight:800;

Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.

Pretty smart :-)

Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.

For example the following link will include both weights 400 and 700:

<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>

jQuery - determine if input element is textbox or select list

If you just want to check the type, you can use jQuery's .is() function,

Like in my case I used below,

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Here are two other solutions

When a module is not yours - try to install types from @types:

npm install -D @types/module-name

If the above install errors - try changing import statements to require:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

How to get Real IP from Visitor?

Try this php code.

<?PHP

function getUserIP()
{
    // Get real visitor IP behind CloudFlare network
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
              $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
              $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 177.87.193.134]


?>

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

Run a Docker image as a container

Get the name or id of the image you would like to run, with this command:

docker images

The Docker run command is used in the following way:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Below I have included the dispatch, name, publish, volume and restart options before specifying the image name or id:

docker run -d --name  container-name -p localhost:80:80 -v $HOME/myContainer/configDir:/myImage/configDir --restart=always image-name

Where:

--detach , -d        Run container in background and print container ID
--name                Assign a name to the container
--publish , -p        Publish a container’s port(s) to the host
--volume , -v        Bind mount a volume
--restart            Restart policy to apply when a container exits

For more information, please check out the official Docker run reference.

How to force a checkbox and text on the same line?

Another way to do this solely with css:

input[type='checkbox'] {
  float: left;
  width: 20px;
}
input[type='checkbox'] + label {
  display: block;
  width: 30px;
}

Note that this forces each checkbox and its label onto a separate line, rather than only doing so only when there's overflow.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

  • Notepad++, Visual Studio, and some others: Alt + drag.
  • vim: Ctrl + v or (bizarrely enough) Quad-click-drag. In windows: Ctrl + Q (since Ctrl + V is the standard for paste)

How to create a HTML Table from a PHP array?

I had a similar need, but my array could contain key/value or key/array or array of arrays, like this array:

$array = array(
    "ni" => "00000000000000",
    "situacaoCadastral" => array(
        "codigo" => 2,
        "data" => "0000-00-00",
        "motivo" => "",
    ),
    "naturezaJuridica" => array(
        "codigo" => "0000",
        "descricao" => "Lorem ipsum dolor sit amet, consectetur",
    ),
    "dataAbertura" => "0000-00-00",
    "cnaePrincipal" => array(
        "codigo" => "0000000",
        "descricao" => "Lorem ips",
    ),
    "endereco" => array(
        "tipoLogradouro" => "Lor",
        "logradouro" => "Lorem i",
        "numero" => "0000",
        "complemento" => "",
        "cep" => "00000000",
        "bairro" => "Lorem ",
        "municipio" => array(
            "codigo" => "0000",
            "descricao" => "Lorem ip",
        ),
    ),
    "uf" => "MS",
    "pais" => array(
        "codigo" => "105",
        "descricao" => "BRASIL",
    ),
    "municipioJurisdicao" => array(
        "codigo" => "0000000",
        "descricao" => "DOURADOS",
    ),
    "telefones" => array(
        array(
            'ddd' => '67',
            'numero' => '00000000',
        ),
    ),
    "correioEletronico" => "[email protected]",
    "capitalSocial" => 0,
    "porte" => "00",
    "situacaoEspecial" => "",
    "dataSituacaoEspecial" => ""
);

The function I created to solve was:

function array_to_table($arr, $first=true, $sub_arr=false){
    $width = ($sub_arr) ? 'width="100%"' : '' ;
    $table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
    $rows = array();
    foreach ($arr as $key => $value):
        $value_type = gettype($value);
        switch ($value_type) {
            case 'string':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
                break;
            case 'integer':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
                break;
            case 'array':
                if (gettype($key) == "integer"):
                    $rows[] = array_to_table($value, false);
                elseif(gettype($key) == "string"):
                    $rows[] = "<tr><td><strong>{$key}</strong></td><td>".
                        array_to_table($value, true, true) . "</td>";
                endif;
                break;
            default:
                # code...
                break;
        }
    endforeach;
    $ROWS = implode("\n", $rows);
    $table .= ($first) ? $ROWS . '</table>' : $ROWS;
    return $table;
}

echo array_to_table($array);

And the output is this

Tips for using Vim as a Java IDE?

I have just uploaded this Vim plugin for the development of Java Maven projects.

And don't forget to set the highlighting if you haven't already:

enter image description here https://github.com/sentientmachine/erics_vim_syntax_and_color_highlighting

sql query to find the duplicate records

If your RDBMS supports the OVER clause...

SELECT
   title
FROM
    (
    select
       title, count(*) OVER (PARTITION BY title) as cnt
    from
      kmovies
    ) T
ORDER BY
   cnt DESC

What are the most common naming conventions in C?

Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.

First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.

Then, the convention:

  • Any names MUST be a readable sentence explaining what you have. Like "this is my convention".
  • Then, 4 methods to get a convention out of a sentence:
    1. THIS_IS_MY_CONVENTION for macros, enum members
    2. ThisIsMyConvention for file name, object name (class, struct, enum, union...), function name, method name, typedef
    3. this_is_my_convention global and local variables,
      parameters, struct and union elements
    4. thisismyconvention [optional] very local and temporary variables (such like a for() loop index)

And that's it.

It gives

class MyClass {
    enum TheEnumeration {
        FIRST_ELEMENT,
        SECOND_ELEMENT,
    }

    int class_variable;

    int MyMethod(int first_param, int second_parameter) {
        int local_variable;
        TheEnumeration local_enum;
        for(int myindex=0, myindex<class_variable, myindex++) {
             localEnum = FIRST_ELEMENT;
        }
    }
}

Google Chrome "window.open" workaround?

I have the same problem, Chrome doesn`t open a new window from code (not handlers).
I found this solution:

setTimeout(function () {
    window.open(
        url, 'name', 'toolbar=1, scrollbars=1, location=1,
        statusbar=0, menubar=1, resizable=1, width=800, height=600'
    );
}, 1);

How to sign in kubernetes dashboard?

A self-explanatory simple one-liner to extract token for kubernetes dashboard login.

kubectl describe secret -n kube-system | grep deployment -A 12

Copy the token and paste it on the kubernetes dashboard under token sign in option and you are good to use kubernetes dashboard

Tkinter scrollbar for frame

We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.

f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)           
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Rails Object to hash

In most recent version of Rails (can't tell which one exactly though), you could use the as_json method :

@post = Post.first
hash = @post.as_json
puts hash.pretty_inspect

Will output :

{ 
  :name => "test",
  :post_number => 20,
  :active => true
}

To go a bit further, you could override that method in order to customize the way your attributes appear, by doing something like this :

class Post < ActiveRecord::Base
  def as_json(*args)
    {
      :name => "My name is '#{self.name}'",
      :post_number => "Post ##{self.post_number}",
    }
  end
end

Then, with the same instance as above, will output :

{ 
  :name => "My name is 'test'",
  :post_number => "Post #20"
}

This of course means you have to explicitly specify which attributes must appear.

Hope this helps.

EDIT :

Also you can check the Hashifiable gem.

How to skip a iteration/loop in while-loop

while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}

How do I change the color of radio buttons?

Try this css with transition:

enter image description here

Demo

$DarkBrown: #292321;

$Orange: #CC3300;

div {
  margin:0 0 0.75em 0;
}

input[type="radio"] {
    display:none;
}
input[type="radio"] + label {
    color: $DarkBrown;
    font-family:Arial, sans-serif;
    font-size:14px;
}
input[type="radio"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    cursor:pointer;
    -moz-border-radius:  50%;
    border-radius:  50%;
}

input[type="radio"] + label span {
     background-color:$DarkBrown;
}

input[type="radio"]:checked + label span{
     background-color:$Orange;
}

input[type="radio"] + label span,
input[type="radio"]:checked + label span {
  -webkit-transition:background-color 0.4s linear;
  -o-transition:background-color 0.4s linear;
  -moz-transition:background-color 0.4s linear;
  transition:background-color 0.4s linear;
}

Html :

<div>
  <input type="radio" id="radio01" name="radio" />
  <label for="radio01"><span></span>Radio Button 1</label>
</div>

<div>
 <input type="radio" id="radio02" name="radio" />
 <label for="radio02"><span></span>Radio Button 2</label>
</div>

Properties file in python (similar to Java Properties)

Here is link to my project: https://sourceforge.net/projects/pyproperties/. It is a library with methods for working with *.properties files for Python 3.x.

But it is not based on java.util.Properties

How to create empty text file from a batch file?

copy NUL EmptyFile.txt

DOS has a few special files (devices, actually) that exist in every directory, NUL being the equivalent of UNIX's /dev/null: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON is occasionally useful as well.

To avoid having any output at all, you can use

copy /y NUL EmptyFile.txt >NUL

/y prevents copy from asking a question you can't see when output goes to NUL.

Using Application context everywhere?

I would use Application Context to get a System Service in the constructor. This eases testing & benefits from composition

public class MyActivity extends Activity {

    private final NotificationManager notificationManager;

    public MyActivity() {
       this(MyApp.getContext().getSystemService(NOTIFICATION_SERVICE));
    }

    public MyActivity(NotificationManager notificationManager) {
       this.notificationManager = notificationManager;
    }

    // onCreate etc

}

Test class would then use the overloaded constructor.

Android would use the default constructor.

SQL Server Group by Count of DateTime Per Hour?

How about this? Assuming SQL Server 2008:

SELECT CAST(StartDate as date) AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

For pre-2008:

SELECT DATEADD(day,datediff(day,0,StartDate),0)   AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

This results in :

ForDate                 | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000     12       3

Spark: Add column to dataframe conditionally

Try withColumn with the function when as follows:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))

newDf.show() shows

+---+----+---+---+
|  A|   B|  C|  D|
+---+----+---+---+
|  4|blah|  2|  1|
|  2|    |  3|  0|
| 56| foo|  3|  1|
|100|null|  5|  0|
+---+----+---+---+

I added the (100, null, 5) row for testing the isNull case.

I tried this code with Spark 1.6.0 but as commented in the code of when, it works on the versions after 1.4.0.

How to find minimum value from vector?

You have an error in your code. This line:

for(int i=0;i<v[n];i++)

should be

for(int i=0;i<n;i++)

because you want to search n places in your vector, not v[n] places (which wouldn't mean anything)

How to stop line breaking in vim

I personnally went for:

  • set wrap,
  • set linebreak
  • set breakindent
  • set showbreak=?.

Some explanation:

  • wrap option visually wraps line instead of having to scroll horizontally
  • linebreak is for wrapping long lines at a specific character instead of just anywhere when the line happens to be too long, like in the middle of a word. By default, it breaks on whitespace (word separator), but you can configure it with breakat. It also does NOT insert EOL in the file as the OP wanted.
  • breakat is the character where it will visually break the line. No need to modify it if you want to break at whitespace between two words.
  • breakindent enables to visually indent the line when it breaks.
  • showbreak enables to set the character which indicates this break.

See :h <keyword> within vim for more info.

Note that you don't need to modify textwidth nor wrapmargin if you go this route.

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Just simply comment out the line: ALLOWED_HOSTS = [...]

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

html text input onchange event

Well unless I misunderstand you can just use the onChange attribute:

<input type="text" onChange="return bar()">

Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

Get Mouse Position

In SWT you need not be in a listener to get at the mouse location. The Display object has the method getCursorLocation().

In vanilla SWT/JFace, call Display.getCurrent().getCursorLocation().

In an RCP application, call PlatformUI.getWorkbench().getDisplay().getCursorLocation().

For SWT applications, it is preferable to use getCursorLocation() over the MouseInfo.getPointerInfo() that others have mentioned, as the latter is implemented in the AWT toolkit that SWT was designed to replace.

Makefile ifeq logical or

You can introduce another variable. It doesnt consolidate both checks, but it at least avoids having to put the body in twice:

do_it = 
ifeq ($(GCC_MINOR), 4)
    do_it = yes
endif
ifeq ($(GCC_MINOR), 5)
    do_it = yes
endif
ifdef do_it
    CFLAGS += -fno-strict-overflow
endif

SQL Server: Null VS Empty String

How are the "NULL" and "empty varchar" values stored in SQL Server. Why would you want to know that? Or in other words, if you knew the answer, how would you use that information?

And in case I have no user entry for a string field on my UI, should I store a NULL or a ''? It depends on the nature of your field. Ask yourself whether the empty string is a valid value for your field.

If it is (for example, house name in an address) then that might be what you want to store (depending on whether or not you know that the address has no house name).

If it's not (for example, a person's name), then you should store a null, because people don't have blank names (in any culture, so far as I know).

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

What is the most accurate way to retrieve a user's correct IP address in PHP?

I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.

What's the key difference between HTML 4 and HTML 5?

Now W3c provides an official difference on their site:

http://www.w3.org/TR/html5-diff/

Browser detection

For browser compatibility you can use this code. This method returns browser name and version :

private string GetBrowserNameWithVersion
{
    var userAgent = Request.UserAgent;
    var browserWithVersion = "";
    if (userAgent.IndexOf("Edge") > -1)
    {
        //Edge
        browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Chrome") > -1)
    {
        //Chrome
        browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Safari") > -1)
    {
        //Safari
        browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Firefox") > -1)
    {
        //Firefox
        browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("rv") > -1)
    {
            //IE11
        browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("MSIE") > -1)
    {
        //IE6-10
        browserWithVersion = "Internet Explorer Browser  Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Other") > -1)
    {
        //Other
        browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
    }

    return browserWithVersion;
}

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

How to disable PHP Error reporting in CodeIgniter?

Change CI index.php file to:

if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

if (defined('ENVIRONMENT')){
    switch (ENVIRONMENT){
        case 'development':
            error_reporting(E_ALL);
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:

$db['default']['db_debug'] = FALSE; 

Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html

$active_group = 'development';


$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;

$db['development']['db_debug'] = TRUE;

$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;



$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;

$db['production']['db_debug'] = FALSE;

$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

django admin - add custom form fields that are not part of the model

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

I want to delete all bin and obj folders to force all projects to rebuild everything

I found this thread and got bingo. A little more searching turned up this power shell script:

Get-ChildItem .\ -include bin,obj -Recurse | ForEach-Object ($_) { Remove-Item $_.FullName -Force -Recurse }

I thought I'd share, considering that I did not find the answer when I was looking here.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

I think that the other posts have answered the question, but just some interesting for your information (from the command prompt):

dir c:\ /ad /x

This will provide a listing of only directories and also provide their "Short names".

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Using R to list all files with a specified extension

Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf

filenames <- Sys.glob("*.dbf")

Find element's index in pandas Series

Another way to do it that hasn't been mentioned yet is the tolist method:

myseries.tolist().index(7)

should return the correct index, assuming the value exists in the Series.

Convert command line argument to string

#include <iostream>

std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

How can I make Visual Studio wrap lines at 80 characters?

Tools >> Options >> Text Editor >> All Languages >> General >> Select Word Wrap.

I dont know if you can select a specific number of columns?

How to shrink temp tablespace in oracle?

Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.

Steps to shrink TEMP Tablespace

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

Case-insensitive string comparison in C++

Are you talking about a dumb case insensitive compare or a full normalized Unicode compare?

A dumb compare will not find strings that might be the same but are not binary equal.

Example:

U212B (ANGSTROM SIGN)
U0041 (LATIN CAPITAL LETTER A) + U030A (COMBINING RING ABOVE)
U00C5 (LATIN CAPITAL LETTER A WITH RING ABOVE).

Are all equivalent but they also have different binary representations.

That said, Unicode Normalization should be a mandatory read especially if you plan on supporting Hangul, Thaï and other asian languages.

Also, IBM pretty much patented most optimized Unicode algorithms and made them publicly available. They also maintain an implementation : IBM ICU

Is it correct to use alt tag for an anchor link?

I used title and it worked!

The title attribute gives the title of the link. With one exception, it is purely advisory. The value is text. The exception is for style sheet links, where the title attribute defines alternative style sheet sets.

<a class="navbar-brand" href="http://www.alberghierocastelnuovocilento.gov.it/sito/index.php" title="sito dell'Istituto Ancel Keys">A.K.</a>

Get int value from enum in C#

In Visual Basic, it should be:

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I encountered this issue when using a different AWS profile. I saw the error when I was using an account with admin permissions, so the possibility of permissions issues seemed unlikely.

It's really a pet peeve of mine that AWS is so prone to issuing error messages that have such little correlation with the required actions, from a user perspective.

Validating parameters to a Bash script

I would use bash's [[:

if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then 
    echo 'Please pass a number that corresponds to a directory'
    exit 1
fi

I found this faq to be a good source of information.

Python Socket Receive Large Amount of Data

You can do it using Serialization

from socket import *
from json import dumps, loads

def recvall(conn):
    data = ""
    while True:
    try:
        data = conn.recv(1024)
        return json.loads(data)
    except ValueError:
        continue

def sendall(conn):
    conn.sendall(json.dumps(data))

NOTE: If you want to shara a file using code above you need to encode / decode it into base64

pthread function from a class

My guess would be this is b/c its getting mangled up a bit by C++ b/c your sending it a C++ pointer, not a C function pointer. There is a difference apparently. Try doing a

(void)(*p)(void) = ((void) *(void)) &c[0].print; //(check my syntax on that cast)

and then sending p.

I've done what your doing with a member function also, but i did it in the class that was using it, and with a static function - which i think made the difference.

How do I remove  from the beginning of a file?

BOM is just a sequence of characters ($EF $BB $BF for UTF-8), so just remove them using scripts or configure the editor so it's not added.

From Removing BOM from UTF-8:

#!/usr/bin/perl
@file=<>;
$file[0] =~ s/^\xEF\xBB\xBF//;
print(@file);

I am sure it translates to PHP easily.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How to change the color of the axis, ticks and labels for a plot in matplotlib

  • For those using pandas.DataFrame.plot(), matplotlib.axes.Axes is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax, which enables the usage of the associated formatting methods.
  • The default plotting backend for pandas, is matplotlib.
import pandas as pd

# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)

# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))

# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red') 
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both')  # 'both' refers to minor and major axes

enter image description here

How to use jQuery to show/hide divs based on radio button selection?

The simple jquery source for the same -

$("input:radio[name='group1']").click(function() {      
    $('.desc').hide();
    $('#' + $("input:radio[name='group1']:checked").val()).show();
});

In order to make it little more appropriate just add checked to first option --

<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>  

remove .desc class from styling and modify divs like --

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>

it will really look good any-ways.

how to stop a for loop

Try to simply use break statement.

Also you can use the following code as an example:

a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]

def check_matr(matr, expVal):    
    for row in matr:
        if len(set(row)) > 1 or set(row).pop() != expVal:
            print 'Wrong'
            break# or return
        else:
            print 'ok'
    else:
        print 'empty'
check_matr(a, 0)
check_matr(b, 0)

How do I print output in new line in PL/SQL?

dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');

or

DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) || 
                     'good' || CHR(13) || CHR(10) ||
                     'morning' || CHR(13) || CHR(10) ||
                     'friends' || CHR(13) || CHR(10) ||);

try it.

The APK file does not exist on disk

Sync, Clean, Rebuild and Invalidate Cache and Restart

None of them worked for me.

I have deleted the APK and output.json files in the release folder and debug folder and then tried sync, clean, and build, then it worked fine.

OR simply Delete folder which has the apk and output.json file (in case of debug/ release)

How to enable PHP's openssl extension to install Composer?

For those who're having the same problem as I was. After doing all the solutions above, still didn't work for me. I found out that, uWamp was creating the PHP.INI file in bin/apache directory. So I had to copy the PHP.INI file into php installation directory, that is, bin/php/phpXXXX directory. This should also be where the php.exe is that you selected from the composer setup.

Hope this helps.

Java, How to get number of messages in a topic in apache kafka

I haven't tried this myself, but it seems to make sense.

You can also use kafka.tools.ConsumerOffsetChecker (source).

How to read file using NPOI

If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions

var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
  // map singleItem
  return new OrderDetails()
  {
    Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),

    // use reusable mapper for re-curring scenarios
    Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),

    Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
    Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
    Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
    UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
    Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),

    // read date and total as string, as they're displayed/formatted on the excel
    DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
    TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
  };
});

Get Folder Size from Windows Command Line

I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:\temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

How do I get a value of datetime.today() in Python that is "timezone aware"?

try pnp_datetime, all the time been used and returned is with timezone, and will not cause any offset-naive and offset-aware issues.

>>> from pnp_datetime.pnp_datetime import Pnp_Datetime
>>>
>>> Pnp_Datetime.utcnow()
datetime.datetime(2020, 6, 5, 12, 26, 18, 958779, tzinfo=<UTC>)

Github Push Error: RPC failed; result=22, HTTP code = 413

I had the same problem but I was using a reverse proxy.

So I had to set

client_max_body_size 50m; 

inside both configure files :

  • on the gitlab nginx web server (as said inside the previous answers)
  • but also on the nginx reverse proxy hosted on the dedicated server.

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

If statement for strings in python?

You want:

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer == "y" or answer == "Y":
  print("this will do the calculation")
else:
  exit()

Or

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer in ["y","Y"]:
  print("this will do the calculation")
else:
  exit()

Note:

  1. It's "if", not "If". Python is case sensitive.
  2. Indentation is important.
  3. There is no colon or semi-colon at the end of python commands.
  4. You want raw_input not input; input evals the input.
  5. "or" gives you the first result if it evaluates to true, and the second result otherwise. So "a" or "b" evaluates to "a", whereas 0 or "b" evaluates to "b". See The Peculiar Nature of and and or.

Read the current full URL with React?

As somebody else mentioned, first you need react-router package. But location object that it provides you with contains parsed url.

But if you want full url badly without accessing global variables, I believe the fastest way to do that would be

...

const getA = memoize(() => document.createElement('a'));
const getCleanA = () => Object.assign(getA(), { href: '' });

const MyComponent = ({ location }) => {
  const { href } = Object.assign(getCleanA(), location);

  ...

href is the one containing a full url.

For memoize I usually use lodash, it's implemented that way mostly to avoid creating new element without necessity.

P.S.: Of course is you're not restricted by ancient browsers you might want to try new URL() thing, but basically entire situation is more or less pointless, because you access global variable in one or another way. So why not to use window.location.href instead?

The value violated the integrity constraints for the column

Delete empty rows from Excel after your last row of data!

Some times empty rows in Excel are still considered as data, therefore trying to import them in a table with one or more non nullable columns violates the constrains of the column.

Solution: select all of the empty rows on your sheet, even those after your last row of data, and click delete rows.

Obviously, if some of your data really does vioalte any of your table's constraints, then just fix your data to match the rules of your database..

How to Bootstrap navbar static to fixed on scroll?

I faced the same problem but the solution that worked for me was:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="row">
    <div class="navbar navbar-inverse navbar-static-top">
        ...
    </div>
</nav>

JavaScript:

document.onscroll = function() {
    if( $(window).scrollTop() > $('header').height() ) {
        $('nav > div.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
    }
    else {
        $('nav > div.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
    }
};

Where header was the banner tag above my navigation bar

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Any way to replace characters on Swift String?

Swift 3 solution based on Ramis' answer:

extension String {
    func withReplacedCharacters(_ characters: String, by separator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        return components(separatedBy: characterSet).joined(separator: separator)
    }
}

Tried to come up with an appropriate function name according to Swift 3 naming convention.

Undo a merge by pull request?

If the pull was the last thing he did then

git reset --hard HEAD~1

Way to get number of digits in an int?

simple solution:

public class long_length {
    long x,l=1,n;
    for (n=10;n<x;n*=10){
        if (x/n!=0){
            l++;
        }
    }
    System.out.print(l);
}

Standardize data columns in R

Before I happened to find this thread, I had the same problem. I had user dependant column types, so I wrote a for loop going through them and getting needed columns scale'd. There are probably better ways to do it, but this solved the problem just fine:

 for(i in 1:length(colnames(df))) {
        if(class(df[,i]) == "numeric" || class(df[,i]) == "integer") {
            df[,i] <- as.vector(scale(df[,i])) }
        }

as.vector is a needed part, because it turned out scale does rownames x 1 matrix which is usually not what you want to have in your data.frame.

How to see docker image contents

With Docker EE for Windows (17.06.2-ee-6 on Hyper-V Server 2016) all contents of Windows Containers can be examined at C:\ProgramData\docker\windowsfilter\ path of the host OS.

No special mounting needed.

Folder prefix can be found by container id from docker ps -a output.

echo key and value of an array without and with loop

array_walk($v, function(&$value, $key) {
   echo $key . '--'. $value;
 });

Learn more about array_walk