Programs & Examples On #Filemtime

File Modification Time, also known as mtime. On a UNIX filesystem, concepts similar to mtime include atime (access time) and ctime (metadata change time).

filemtime "warning stat failed for"

For me the filename involved was appended with a querystring, which this function didn't like.

$path = 'path/to/my/file.js?v=2'

Solution was to chop that off first:

$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);

How do I find the parent directory in C#?

Since nothing else I have found helps to solve this in a truly normalized way, here is another answer.

Note that some answers to similar questions try to use the Uri type, but that struggles with trailing slashes vs. no trailing slashes too.

My other answer on this page works for operations that put the file system to work, but if we want to have the resolved path right now (such as for comparison reasons), without going through the file system, C:/Temp/.. and C:/ would be considered different. Without going through the file system, navigating in that manner does not provide us with a normalized, properly comparable path.

What can we do?

We will build on the following discovery:

Path.GetDirectoryName(path + "/") ?? "" will reliably give us a directory path without a trailing slash.

  • Adding a slash (as string, not as char) will treat a null path the same as it treats "".
  • GetDirectoryName will refrain from discarding the last path component thanks to the added slash.
  • GetDirectoryName will normalize slashes and navigational dots.
  • This includes the removal of any trailing slashes.
  • This includes collapsing .. by navigating up.
  • GetDirectoryName will return null for an empty path, which we coalesce to "".

How do we use this?

First, normalize the input path:

dirPath = Path.GetDirectoryName(dirPath + "/") ?? "";

Then, we can get the parent directory, and we can repeat this operation any number of times to navigate further up:

// This is reliable if path results from this or the previous operation
path = Path.GetDirectoryName(path);

Note that we have never touched the file system. No part of the path needs to exist, as it would if we had used DirectoryInfo.

Fastest way to check if a string is JSON in PHP?

This will do it:

function isJson($string) {
    $decoded = json_decode($string); // decode our JSON string
    if ( !is_object($decoded) && !is_array($decoded) ) {
        /*
        If our string doesn't produce an object or array
        it's invalid, so we should return false
        */
        return false;
    }
    /*
    If the following line resolves to true, then there was
    no error and our JSON is valid, so we return true.
    Otherwise it isn't, so we return false.
    */
    return (json_last_error() == JSON_ERROR_NONE);
}

if ( isJson($someJsonString) ) {
    echo "valid JSON";
} else {
    echo "not valid JSON";
}

As shown in other answers, json_last_error() returns any error from our last json_decode(). However there are some edge use cases where this function alone is not comprehensive enough. For example, if you json_decode() an integer (eg: 123), or a string of numbers with no spaces or other characters (eg: "123"), the json_last_error() function will not catch an error.

To combat this, I've added an extra step that ensures the result of our json_decode() is either an object or an array. If it's not, then we return false.

To see this in action, check these two examples:

How to Find And Replace Text In A File With C#

This code Worked for me

- //-------------------------------------------------------------------
                           // Create an instance of the Printer
                           IPrinter printer = new Printer();

                           //----------------------------------------------------------------------------
                           String path = @"" + file_browse_path.Text;
                         //  using (StreamReader sr = File.OpenText(path))

                           using (StreamReader sr = new System.IO.StreamReader(path))
                           {

                              string fileLocMove="";
                              string newpath = Path.GetDirectoryName(path);
                               fileLocMove = newpath + "\\" + "new.prn";



                                  string text = File.ReadAllText(path);
                                  text= text.Replace("<REF>", reference_code.Text);
                                  text=   text.Replace("<ORANGE>", orange_name.Text);
                                  text=   text.Replace("<SIZE>", size_name.Text);
                                  text=   text.Replace("<INVOICE>", invoiceName.Text);
                                  text=   text.Replace("<BINQTY>", binQty.Text);
                                  text = text.Replace("<DATED>", dateName.Text);

                                       File.WriteAllText(fileLocMove, text);



                               // Print the file
                               printer.PrintRawFile("Godex G500", fileLocMove, "n");
                              // File.WriteAllText("C:\\Users\\Gunjan\\Desktop\\new.prn", s);
                           }

How to insert a character in a string at a certain position?

As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs:

This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Usage :

String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

Or if you need synchronization use the StringBuffer with similar usage :

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();

How to find out what type of a Mat object is with Mat::type() in OpenCV

I've added some usability to the function from the answer by @Octopus, for debugging purposes.

void MatType( Mat inputMat )
{
    int inttype = inputMat.type();

    string r, a;
    uchar depth = inttype & CV_MAT_DEPTH_MASK;
    uchar chans = 1 + (inttype >> CV_CN_SHIFT);
    switch ( depth ) {
        case CV_8U:  r = "8U";   a = "Mat.at<uchar>(y,x)"; break;  
        case CV_8S:  r = "8S";   a = "Mat.at<schar>(y,x)"; break;  
        case CV_16U: r = "16U";  a = "Mat.at<ushort>(y,x)"; break; 
        case CV_16S: r = "16S";  a = "Mat.at<short>(y,x)"; break; 
        case CV_32S: r = "32S";  a = "Mat.at<int>(y,x)"; break; 
        case CV_32F: r = "32F";  a = "Mat.at<float>(y,x)"; break; 
        case CV_64F: r = "64F";  a = "Mat.at<double>(y,x)"; break; 
        default:     r = "User"; a = "Mat.at<UKNOWN>(y,x)"; break; 
    }   
    r += "C";
    r += (chans+'0');
    cout << "Mat is of type " << r << " and should be accessed with " << a << endl;

}

R: Comment out block of code

Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.

It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.

These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.

How to timeout a thread

BalusC said:

Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().

But if you replace Thread.sleep(4000); with for (int i = 0; i < 5E8; i++) {} then it doesn't compile, because the empty loop doesn't throw an InterruptedException.

And for the thread to be interruptible, it needs to throw an InterruptedException.

This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.

Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]

how do you pass images (bitmaps) between android activities using bundles?

If you pass it as a Parcelable, you're bound to get a JAVA BINDER FAILURE error. So, the solution is this: If the bitmap is small, like, say, a thumbnail, pass it as a byte array and build the bitmap for display in the next activity. For instance:

in your calling activity...

Intent i = new Intent(this, NextActivity.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);

...and in your receiving activity

if(getIntent().hasExtra("byteArray")) {
    ImageView previewThumbnail = new ImageView(this);
    Bitmap b = BitmapFactory.decodeByteArray(
        getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);        
    previewThumbnail.setImageBitmap(b);
}

How to Query Database Name in Oracle SQL Developer?

Once I realized I was running an Oracle database, not MySQL, I found the answer

select * from v$database;

or

select ora_database_name from dual;

Try both. Credit and source goes to: http://www.perlmonks.org/?node_id=520376.

jQuery get the image src

for full url use

$('#imageContainerId').prop('src')

for relative image url use

$('#imageContainerId').attr('src')

_x000D_
_x000D_
function showImgUrl(){_x000D_
  console.log('for full image url ' + $('#imageId').prop('src') );_x000D_
  console.log('for relative image url ' + $('#imageId').attr('src'));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>_x000D_
_x000D_
<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
_x000D_
_x000D_
_x000D_

jQuery ui datepicker with Angularjs

Here is my code-

var datePicker = angular.module('appointmentApp', []);

datePicker.directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'dd-mm-yy',
                onSelect: function (date) {
                    scope.appoitmentScheduleDate = date;
                    scope.$apply();
                }
            });
        }
    };
});

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Running AngularJS initialization code when view is loaded

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

CSS text-overflow in a table cell?

To clip text with an ellipsis when it overflows a table cell, you will need to set the max-width CSS property on each td class for the overflow to work. No extra layout div elements are required:

td
{
 max-width: 100px;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}

For responsive layouts; use the max-width CSS property to specify the effective minimum width of the column, or just use max-width: 0; for unlimited flexibility. Also, the containing table will need a specific width, typically width: 100%;, and the columns will typically have their width set as percentage of the total width

table {width: 100%;}
td
{
 max-width: 0;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}
td.column_a {width: 30%;}
td.column_b {width: 70%;}

Historical: For IE 9 (or less) you need to have this in your HTML, to fix an IE-specific rendering issue

<!--[if IE]>
<style>
table {table-layout: fixed; width: 100px;}
</style>
<![endif]-->

Android Studio: Application Installation Failed

I had the same issue but finally it worked after storage clean on my mobile. May be happen because of insufficient storage

CMAKE_MAKE_PROGRAM not found

I had the same problem which is solved using the following:

Try to rename all the folders to not to be more than 8 characters and without spaces.

How to get instance variables in Python?

Sometimes you want to filter the list based on public/private vars. E.g.

def pub_vars(self):
    """Gives the variable names of our instance we want to expose
    """
    return [k for k in vars(self) if not k.startswith('_')]

Best way to use multiple SSH private keys on one client

I had run into this issue a while back, when I had two Bitbucket accounts and wanted to had to store separate SSH keys for both. This is what worked for me.

I created two separate ssh configurations as follows.

Host personal.bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /Users/username/.ssh/personal
Host work.bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /Users/username/.ssh/work

Now when I had to clone a repository from my work account - the command was as follows.

git clone [email protected]:teamname/project.git

I had to modify this command to:

git clone git@**work**.bitbucket.org:teamname/project.git

Similarly the clone command from my personal account had to be modified to

git clone git@personal.bitbucket.org:name/personalproject.git

Refer this link for more information.

How to print to the console in Android Studio?

Android Studio 3.0 and earlier:

If the other solutions don't work, you can always see the output in the Android Monitor.


android studio screen shot


Make sure to set your filter to Show only selected application or create a custom filter.

enter image description here

VS 2017 Metadata file '.dll could not be found

Check all the projects are loaded. In my case one of the project was unloaded and reloading the project clears the errors.

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

json_encode/json_decode - returns stdClass instead of Array in PHP

    var_dump(json_decode('{"0":0}'));    // output: object(0=>0)
    var_dump(json_decode('[0]'));          //output: [0]

    var_dump(json_decode('{"0":0}', true));//output: [0]
    var_dump(json_decode('[0]', true));    //output: [0]

If you decode the json into array, information will be lost in this situation.

What is the difference between children and childNodes in JavaScript?

Understand that .children is a property of an Element. 1 Only Elements have .children, and these children are all of type Element. 2

However, .childNodes is a property of Node. .childNodes can contain any node. 3

A concrete example would be:

let el = document.createElement("div");
el.textContent = "foo";

el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0;   // No Element children.

Most of the time, you want to use .children because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.

If you do want to manipulate Text nodes, you probably want .textContent instead. 4


1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes can hold any node because it is a NodeList.
4. Or .innerText. See the differences here or here.

How do I convert an NSString value to NSData?

NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

How can I control the width of a label tag?

Using the inline-block is better because it doesn't force the remaining elements and/or controls to be drawn in a new line.

label {
  width:200px;
  display: inline-block;
}

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
    console.log(something);
  };
  useEffect(() => {
    saySomething("from useEffect");
  });
  const handleClick = (e) => {
    saySomething("element clicked");
  };
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World
    </Button>
  );
};

ReactDOM.render(<App />, document.querySelector("#app"));

https://codesandbox.io/s/currying-meadow-gm9g0

Checkboxes in web pages – how to make them bigger?

I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:

First the HTML code:

<span role="checkbox"/>

Then the CSS:

[role=checkbox]{
    background-image: url(../img/checkbox_nc.png);
    height: 15px;
    width: 15px;
    display: inline-block;
    margin: 0 5px 0 5px;
    cursor: pointer;
}

.checked[role=checkbox]{
    background-image: url(../img/checkbox_c.png);
}

To toggle checkbox state, I used JQuery:

CLICKEVENT='touchend';
function createCheckboxes()
{
    $('[role=checkbox]').bind(CLICKEVENT,function()
    {
        $(this).toggleClass('checked');
    });
}

But It can easily be done without it...

Hope it can help!

Laravel Mail::send() sending to multiple to or bcc addresses

the accepted answer does not work any longer with laravel 5.3 because mailable tries to access ->email and results in

ErrorException in Mailable.php line 376: Trying to get property of non-object

a working code for laravel 5.3 is this:

$users_temp = explode(',', '[email protected],[email protected]');
    $users = [];
    foreach($users_temp as $key => $ut){
      $ua = [];
      $ua['email'] = $ut;
      $ua['name'] = 'test';
      $users[$key] = (object)$ua;
    }
 Mail::to($users)->send(new OrderAdminSendInvoice($o));

How to find all combinations of coins when given some dollar value

Both: iterate through all denominations from high to low, take one of denomination, subtract from requried total, then recurse on remainder (constraining avilable denominations to be equal or lower to current iteration value.)

What is the difference between for and foreach?

foreach syntax is quick and easy. for syntax is a little more complex, but is also more flexible.

foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items.

The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.

Bottom line- use foreach to quickly iterate all of the items in a collection. Use for to iterate a subset of the items of the collection or to modify the items as they are iterated.

How to run python script on terminal (ubuntu)?

Save your python file in a spot where you will be able to find it again. Then navigate to that spot using the command line (cd /home/[profile]/spot/you/saved/file) or go to that location with the file browser. If you use the latter, right click and select "Open In Terminal." When the terminal opens, type "sudo chmod +x Yourfilename." After entering your password, type "python ./Yourfilename" which will open your python file in the command line. Hope this helps!

Running Linux Mint

How to $watch multiple variable change in angular

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Pass variables by reference in JavaScript

Simple Object

_x000D_
_x000D_
function foo(x) {
  // Function with other context
  // Modify `x` property, increasing the value
  x.value++;
}

// Initialize `ref` as object
var ref = {
  // The `value` is inside `ref` variable object
  // The initial value is `1`
  value: 1
};

// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);

console.log(ref.value); // Prints "3"
_x000D_
_x000D_
_x000D_


Custom Object

Object rvar

_x000D_
_x000D_
/**
 * Aux function to create by-references variables
 */
function rvar(name, value, context) {
  // If `this` is a `rvar` instance
  if (this instanceof rvar) {
    // Inside `rvar` context...
    
    // Internal object value
    this.value = value;
    
    // Object `name` property
    Object.defineProperty(this, 'name', { value: name });
    
    // Object `hasValue` property
    Object.defineProperty(this, 'hasValue', {
      get: function () {
        // If the internal object value is not `undefined`
        return this.value !== undefined;
      }
    });
    
    // Copy value constructor for type-check
    if ((value !== undefined) && (value !== null)) {
      this.constructor = value.constructor;
    }
    
    // To String method
    this.toString = function () {
      // Convert the internal value to string
      return this.value + '';
    };
  } else {
    // Outside `rvar` context...
    
    // Initialice `rvar` object
    if (!rvar.refs) {
      rvar.refs = {};
    }
    
    // Initialize context if it is not defined
    if (!context) {
      context = window;
    }
    
    // Store variable
    rvar.refs[name] = new rvar(name, value, context);
    
    // Define variable at context
    Object.defineProperty(context, name, {
      // Getter
      get: function () { return rvar.refs[name]; },
      // Setter
      set: function (v) { rvar.refs[name].value = v; },
      // Can be overrided?
      configurable: true
    });

    // Return object reference
    return context[name];
  }
}

// Variable Declaration

  // Declare `test_ref` variable
  rvar('test_ref_1');

  // Assign value `5`
  test_ref_1 = 5;
  // Or
  test_ref_1.value = 5;

  // Or declare and initialize with `5`:
  rvar('test_ref_2', 5);

// ------------------------------
// Test Code

// Test Function
function Fn1 (v) { v.value = 100; }

// Declare
rvar('test_ref_number');

// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);

// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);

// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);

// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);

// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');

// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');

// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true

// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true

// Increase value
test_ref_number++;
test_ref_number.value === 101; // true

// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true

test_ref_str.value === "a"; // true

// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true 
_x000D_
_x000D_
_x000D_

Android Webview - Webpage should fit the device screen

webview.setInitialScale(1);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setJavaScriptEnabled(true);

will work, but remember to remove something like:

<meta name="viewport" content="user-scalable=no"/>

if existed in the html file or change user-scalable=yes, otherwise it won't.

How do I enable C++11 in gcc?

As previously mentioned - in case of a project, Makefile or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.

But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out?

Well, I would much like to have some #pragma to turn in on at source level, or maybe a default extension - say .cxx or .C11 or whatever, trigger it by default. But as of today, there is no such feature.

But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc (or whatever):

alias g++11="g++ -std=c++0x"

or, for newer G++ (and when you want to feel "real C++11")

alias g++11="g++ -std=c++11"

You can even alias to g++ itself, if you hate C++03 that much ;)

How do I copy a version of a single file from one git branch to another?

Run this from the branch where you want the file to end up:

git checkout otherbranch myfile.txt

General formulas:

git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>

Some notes (from comments):

  • Using the commit hash you can pull files from any commit
  • This works for files and directories
  • overwrites the file myfile.txt and mydir
  • Wildcards don't work, but relative paths do
  • Multiple paths can be specified

an alternative:

git show commit_id:path/to/file > path/to/file

What is WebKit and how is it related to CSS?

Webkit is the html/css rendering engine used in Apple's Safari browser, and in Google's Chrome. css values prefixes with -webkit- are webkit-specific, they're usually CSS3 or other non-standardised features.

to answer update 2 w3c is the body that tries to standardize these things, they write the rules, then programmers write their rendering engine to interpret those rules. So basically w3c says DIVs should work "This way" the engine-writer then uses that rule to write their code, any bugs or mis-interpretations of the rules cause the compatibility issues.

How to read an entire file to a string using C#?

@Cris sorry .This is quote MSDN Microsoft

Methodology

In this experiment, two classes will be compared. The StreamReader and the FileStream class will be directed to read two files of 10K and 200K in their entirety from the application directory.

StreamReader (VB.NET)

sr = New StreamReader(strFileName)
Do
  line = sr.ReadLine()
Loop Until line Is Nothing
sr.Close()

FileStream (VB.NET)

Dim fs As FileStream
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Dim b(1024) As Byte
fs = File.OpenRead(strFileName)
Do While fs.Read(b, 0, b.Length) > 0
    temp.GetString(b, 0, b.Length)
Loop
fs.Close()

Result

enter image description here

FileStream is obviously faster in this test. It takes an additional 50% more time for StreamReader to read the small file. For the large file, it took an additional 27% of the time.

StreamReader is specifically looking for line breaks while FileStream does not. This will account for some of the extra time.

Recommendations

Depending on what the application needs to do with a section of data, there may be additional parsing that will require additional processing time. Consider a scenario where a file has columns of data and the rows are CR/LF delimited. The StreamReader would work down the line of text looking for the CR/LF, and then the application would do additional parsing looking for a specific location of data. (Did you think String. SubString comes without a price?)

On the other hand, the FileStream reads the data in chunks and a proactive developer could write a little more logic to use the stream to his benefit. If the needed data is in specific positions in the file, this is certainly the way to go as it keeps the memory usage down.

FileStream is the better mechanism for speed but will take more logic.

How to set a dropdownlist item as selected in ASP.NET?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.

dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;

You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue

dropdownlist.ClearSelection();  
dropdownlist.Items.FindByValue(value).Selected = true;

Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.

If you expect that you may be looking for text/value that wont be present in DropDownList ListItem collection then you must check if you get the ListItem object or null from FindByText or FindByValue before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.

ListItem listItem = dropdownlist.Items.FindByValue(value);

if(listItem != null) 
{
   dropdownlist.ClearSelection();
   listItem.Selected = true;
}

What's a "static method" in C#?

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the membe

Uploading both data and files in one form using Ajax?

you can just append them on your formdata, add your files and datas in it.you can read this..

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.

display HTML page after loading complete

The easiest thing to do is putting a div with the following CSS in the body:

#hideAll
 {
   position: fixed;
   left: 0px; 
   right: 0px; 
   top: 0px; 
   bottom: 0px; 
   background-color: white;
   z-index: 99; /* Higher than anything else in the document */

 }

(Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser)

Add the DIV like so (directly after the opening body tag):

<div style="display: none" id="hideAll">&nbsp;</div>

show the DIV directly after :

 <script type="text/javascript">
   document.getElementById("hideAll").style.display = "block";
 </script> 

and hide it onload:

 window.onload = function() 
  { document.getElementById("hideAll").style.display = "none"; }

or using jQuery

 $(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });

this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.

How to check if a character is upper-case in Python?

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

So you can write it in 1 string

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

For this particular purpose, $("span").show() should be good enough.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

How to enable local network users to access my WAMP sites?

In WAMPServer 3 you dont do this in httpd.conf

Instead edit \wamp\bin\apache\apache{version}\conf\extra\httpd-vhost.conf and do the same chnage to the Virtual Host defined for localhost

WAMPServer 3 comes with a Virtual Host pre defined for localhost

Why does modern Perl avoid UTF-8 by default?

We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.

There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".

As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.

If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.

`

Changing the "tick frequency" on x or y axis in matplotlib?

Pure Python Implementation

Below's a pure python implementation of the desired functionality that handles any numeric series (int or float) with positive, negative, or mixed values and allows for the user to specify the desired step size:

import math

def computeTicks (x, step = 5):
    """
    Computes domain with given step encompassing series x
    @ params
    x    - Required - A list-like object of integers or floats
    step - Optional - Tick frequency
    """
    xMax, xMin = math.ceil(max(x)), math.floor(min(x))
    dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
    return range(dMin, dMax, step)

Sample Output

# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))

[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))

[-30, -25, -20, -15, -10, -5, 0]

# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))

[15, 20, 25, 30]

# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))

[0, 5, 10, 15, 20, 25]

# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))

[100, 200, 300, 400, 500, 600, 700, 800]

Sample Usage

import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()

Plot of sample usage

Notice the x-axis has integer values all evenly spaced by 5, whereas the y-axis has a different interval (the matplotlib default behavior, because the ticks weren't specified).

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Insert node at a certain position in a linked list C++

Try this function.

structure of node object:

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int);
    ~Node();
    void setData(int);
    int getData();
    void setNext(Node*);
    Node* getNext();
};

Implementation of the function:

Returning a status value is always a god practice, constants defined here are meant for debugging/logging the application usage.

//constants
static int const SUCCESS = 0;
static int const FAILURE = 1;
static int const NULL_OBJ = 2;
static int const POS_EXCEED = 3;

int addAt(int data, int pos){
    Node *tmp = new Node(data);
    if (tmp == NULL){
        //print for debugging only.
        cout << "Object not created. Out of memory maybe" << endl;
        return NULL_OBJ;
    }
    if (pos == 0){
        // add at beginning
        tmp->setNext(this->head);
        this->head = tmp;
        return SUCCESS;
    }else{
        // add element in between or at end
        int counter = 1;
        Node* currentNode = this->head;
        while (counter < pos && currentNode->getNext() != NULL){
            currentNode= currentNode->getNext();
            counter++;
       }
       tmp->setNext(currentNode->getNext());
       currentNode->setNext(tmp);
       return SUCCESS;
   }
   cout << "Failed due to unknown reason.";
   return FAILURE;
}

Assumption here is that, you will call the function after validating the inputs (data and position). Though we can validate the parameters inside the function, it is not a good practice.

Hope this helps.

How can I format bytes a cell in Excel as KB, MB, GB etc?

I use CDH hadoop and when I export excel report, I have two problems;

1) convert Linux date to excel date,
For that, add an empty column next to date column lets say the top row is B4, paste below formula and drag the BLACK "+" all the way to your last day at the end of the column. Then hide the original column

=(((B4/1000/60)/60)/24)+DATE(1970|1|1)+(-5/24)

2) Convert disk size from byte to TB, GB, and MB
the best formula for that is this

[>999999999999]# ##0.000,,,," TB";[>999999999]# ##0.000,,," GB";# ##0.000,," MB"

it will give you values with 3 decimals just format cells --> Custom and paste the above code there

HTTP vs HTTPS performance

There's a very simple answer to this: Profile the performance of your web server to see what the performance penalty is for your particular situation. There are several tools out there to compare the performance of an HTTP vs HTTPS server (JMeter and Visual Studio come to mind) and they are quite easy to use.

No one can give you a meaningful answer without some information about the nature of your web site, hardware, software, and network configuration.

As others have said, there will be some level of overhead due to encryption, but it is highly dependent on:

  • Hardware
  • Server software
  • Ratio of dynamic vs static content
  • Client distance to server
  • Typical session length
  • Etc (my personal favorite)
  • Caching behavior of clients

In my experience, servers that are heavy on dynamic content tend to be impacted less by HTTPS because the time spent encrypting (SSL-overhead) is insignificant compared to content generation time.

Servers that are heavy on serving a fairly small set of static pages that can easily be cached in memory suffer from a much higher overhead (in one case, throughput was havled on an "intranet").

Edit: One point that has been brought up by several others is that SSL handshaking is the major cost of HTTPS. That is correct, which is why "typical session length" and "caching behavior of clients" are important.

Many, very short sessions means that handshaking time will overwhelm any other performance factors. Longer sessions will mean the handshaking cost will be incurred at the start of the session, but subsequent requests will have relatively low overhead.

Client caching can be done at several steps, anywhere from a large-scale proxy server down to the individual browser cache. Generally HTTPS content will not be cached in a shared cache (though a few proxy servers can exploit a man-in-the-middle type behavior to achieve this). Many browsers cache HTTPS content for the current session and often times across sessions. The impact the not-caching or less caching means clients will retrieve the same content more frequently. This results in more requests and bandwidth to service the same number of users.

Save results to csv file with Python

You can save it as follow if you have Pandas Dataframe

   df.to_csv(r'/dir/filename.csv')

How to use type: "POST" in jsonp ajax call

If you just want to do a form POST to your own site using $.ajax() (for example, to emulate an AJAX experience), then you can use the jQuery Form Plugin. However, if you need to do a form POST to a different domain, or to your own domain but using a different protocol (a non-secure http: page posting to a secure https: page), then you'll come upon cross-domain scripting restrictions that you won't be able to resolve with jQuery alone (more info). In such cases, you'll need to bring out the big guns: YQL. Put plainly, YQL is a web scraping language with a SQL-like syntax that allows you to query the entire internet as one large table. As it stands now, in my humble opinion YQL is the only [easy] way to go if you want to do cross-domain form POSTing using client-side JavaScript.

More specifically, you'll need to use YQL's Open Data Table containing an Execute block to make this happen. For a good summary on how to do this, you can read the article "Scraping HTML documents that require POST data with YQL". Luckily for us, YQL guru Christian Heilmann has already created an Open Data Table that handles POST data. You can play around with Christian's "htmlpost" table on the YQL Console. Here's a breakdown of the YQL syntax:

  • select * - select all columns, similar to SQL, but in this case the columns are XML elements or JSON objects returned by the query. In the context of scraping web pages, these "columns" generally correspond to HTML elements, so if want to retrieve only the page title, then you would use select head.title.
  • from htmlpost - what table to query; in this case, use the "htmlpost" Open Data Table (you can use your own custom table if this one doesn't suit your needs).
  • url="..." - the form's action URI.
  • postdata="..." - the serialized form data.
  • xpath="..." - the XPath of the nodes you want to include in the response. This acts as the filtering mechanism, so if you want to include only <p> tags then you would use xpath="//p"; to include everything you would use xpath="//*".

Click 'Test' to execute the YQL query. Once you are happy with the results, be sure to (1) click 'JSON' to set the response format to JSON, and (2) uncheck "Diagnostics" to minimize the size of the JSON payload by removing extraneous diagnostics information. The most important bit is the URL at the bottom of the page -- this is the URL you would use in a $.ajax() statement.

Here, I'm going to show you the exact steps to do a cross-domain form POST via a YQL query using this sample form:

<form id="form-post" action="https://www.example.com/add/member" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <button type="button" onclick="doSubmit()">Add Member</button>
</form>

Your JavaScript would look like this:

function doSubmit() {
  $.ajax({
    url: '//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlpost%20where%0Aurl%3D%22' +
         encodeURIComponent($('#form-post').attr('action')) + '%22%20%0Aand%20postdata%3D%22' +
         encodeURIComponent($('#form-post').serialize()) +
         '%22%20and%20xpath%3D%22%2F%2F*%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=',
    dataType: 'json', /* Optional - jQuery autodetects this by default */
    success: function(response) {
      console.log(response);
    }
  });
}

The url string is the query URL copied from the YQL Console, except with the form's encoded action URI and serialized input data dynamically inserted.

NOTE: Please be aware of security implications when passing sensitive information over the internet. Ensure the page you are submitting sensitive information from is secure (https:) and using TLS 1.x instead of SSL 3.0.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

double value = 2.3d;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "-";
string x = value.ToString(nfi);

The result? "2-3"

The model backing the <Database> context has changed since the database was created

None of these solutions would work for us (other than disabling the schema checking altogether). In the end we had a miss-match in our version of Newtonsoft.json

Our AppConfig did not get updated correctly:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
  </dependentAssembly>

The solution was to correct the assembly version to the one we were actually deploying

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="10.0.0.0" />
  </dependentAssembly>

C++ multiline string literal

In C++11 you have raw string literals. Sort of like here-text in shells and script languages like Python and Perl and Ruby.

const char * vogon_poem = R"V0G0N(
             O freddled gruntbuggly thy micturations are to me
                 As plured gabbleblochits on a lurgid bee.
              Groop, I implore thee my foonting turlingdromes.   
           And hooptiously drangle me with crinkly bindlewurdles,
Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't.

                (by Prostetnic Vogon Jeltz; see p. 56/57)
)V0G0N";

All the spaces and indentation and the newlines in the string are preserved.

These can also be utf-8|16|32 or wchar_t (with the usual prefixes).

I should point out that the escape sequence, V0G0N, is not actually needed here. Its presence would allow putting )" inside the string. In other words, I could have put

                "(by Prostetnic Vogon Jeltz; see p. 56/57)"

(note extra quotes) and the string above would still be correct. Otherwise I could just as well have used

const char * vogon_poem = R"( ... )";

The parens just inside the quotes are still needed.

SQL Server: Make all UPPER case to Proper Case/Title Case

If you're in SSIS importing data that has mixed cased and need to do a lookup on a column with proper case, you'll notice that the lookup fails where the source is mixed and the lookup source is proper. You'll also notice you can't use the right and left functions is SSIS for SQL Server 2008r2 for derived columns. Here's a solution that works for me:

UPPER(substring(input_column_name,1,1)) + LOWER(substring(input_column_name, 2, len(input_column_name)-1))

How to dispatch a Redux action with a timeout?

It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

componentDidMount() {
  this.tm = setTimeout(function() {
    setStore({ age: 20 });
  }, 3000);
}

componentWillUnmount() {
  clearTimeout(this.tm);
}

What is the difference between function and procedure in PL/SQL?

In dead simple way it makes this meaning.

Functions :

These subprograms return a single value; mainly used to compute and return a value.

Procedure :

These subprograms do not return a value directly; mainly used to perform an action.

Example Program:

CREATE OR REPLACE PROCEDURE greetings

BEGIN 

dbms_output.put_line('Hello World!');

END ;
/

Executing a Standalone Procedure :

A standalone procedure can be called in two ways:

• Using the EXECUTE keyword • Calling the name of procedure from a PL/SQL block

The procedure can also be called from another PL/SQL block:

BEGIN 
greetings;
END;
/

Function:

CREATE OR REPLACE FUNCTION totalEmployees 
RETURN number IS
total number(3) := 0;
BEGIN 
SELECT count(*) into total 
FROM employees;
RETURN total; 
END;
/

Following program calls the function totalCustomers from an another block

DECLARE 
c number(3);
BEGIN 
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/

Why maven settings.xml file is not there?

settings.xml is not required (and thus not autocreated in ~/.m2 folder) unless you want to change the default settings.

Standalone maven and the maven in eclipse will use the same local repository (~/.m2 folder). This means if some artifacts/dependencies are downloaded by standalone maven, it will not be again downloaded by maven in eclipse.

Based on the version of Eclipse that you use, you may have different maven version in eclipse compared to the standalone. It should not matter in most cases.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

you should change

@Test
public static void testmethod(){}

to

@Test
public void testmethod(){}

the @Test is unsupport static method

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Changing all files' extensions in a folder with one command on Windows

An alternative way to rename files using the renamer npm package.

below is an example of renaming files extensions

renamer -d --path-element ext --find ts --replace js *

Checking version of angular-cli that's installed?

angular cli can report its version when you run it with the version flag

ng --version

Mysql select distinct

You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.

function declaration isn't a prototype

Quick answer: change int testlib() to int testlib(void) to specify that the function takes no arguments.

A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).

A non-prototype function declaration like

int foo();

is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.

For a function that takes one or more arguments, you can specify the type of each argument in the declaration:

int bar(int x, double y);

Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that an argument but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void keyword:

int foo(void); /* foo takes no arguments */

A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:

int testlib()
{
    /* code that implements testlib */
}

This provides a non-prototype declaration for testlib. As a definition, this tells the compiler that testlib has no parameters, but as a declaration, it only tells the compiler that testlib takes some unspecified but fixed number and type(s) of arguments.

If you change () to (void) the declaration becomes a prototype.

The advantage of a prototype is that if you accidentally call testlib with one or more arguments, the compiler will diagnose the error.

(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void) syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the () in C++ and the (void) syntax in C.)

Postgres: clear entire database before re-creating / re-populating from bash script

If you want to clean your database named "example_db":

1) Login to another db(for example 'postgres'):

psql postgres

2) Remove your database:

DROP DATABASE example_db;

3) Recreate your database:

CREATE DATABASE example_db;

Exception thrown inside catch block - will it be caught again?

No. It's very easy to check.

public class Catch {
    public static void main(String[] args) {
        try {
            throw new java.io.IOException();
        } catch (java.io.IOException exc) {
            System.err.println("In catch IOException: "+exc.getClass());
            throw new RuntimeException();
        } catch (Exception exc) {
            System.err.println("In catch Exception: "+exc.getClass());
        } finally {
            System.err.println("In finally");
        }
    }
}

Should print:

In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
        at Catch.main(Catch.java:8)

Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).

Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.

Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).

How to replace master branch in Git, entirely, from another branch?

You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:

git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks

The result should be your master is now essentially seotweaks.

(-s ours is short for --strategy=ours)

From the docs about the 'ours' strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

How to get store information in Magento?

Great answers here. If you're looking for the default view "Store Name" set in the Magento configuration:

Mage::app()->getStore()->getFrontendName()

Module AppRegistry is not registered callable module (calling runApplication)

Worked for me for below version and on iOS

 "react": "16.9.0",
 "react-native": "0.61.5",

Step to resolve Close the current running Metro Bundler Try Re-run your Metro Bundler and check if this issue persists

Hope this will help !

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

Copying a HashMap in Java

The difference is that in C++ your object is on the stack, whereas in Java, your object is in the heap. If A and B are Objects, any time in Java you do:

B = A

A and B point to the same object, so anything you do to A you do to B and vice versa.

Use new HashMap() if you want two different objects.

And you can use Map.putAll(...) to copy data between two Maps.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

Java Compare Two Lists

public static boolean compareList(List ls1, List ls2){
    return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
     }

public static void main(String[] args) {

    ArrayList<String> one = new ArrayList<String>();
    one.add("one");
    one.add("two");
    one.add("six");

    ArrayList<String> two = new ArrayList<String>();
    two.add("one");
    two.add("six");
    two.add("two");

    System.out.println("Output1 :: " + compareList(one, two));

    two.add("ten");

    System.out.println("Output2 :: " + compareList(one, two));
  }

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

Disabling contextual LOB creation as createClob() method threw error

As you noticed, this exception isn't a real problem. It happens during the boot, when Hibernate tries to retrieve some meta information from the database. If this annoys you, you can disable it:

hibernate.temp.use_jdbc_metadata_defaults false

How to create jar file with package structure?

To avoid to add sources files .java to your package you should do

cd src/
jar cvf mylib.jar com/**/*.class

Supposed that your project structure was like

myproject/
    src/
      com/
        mycompany/
          mainClass.java
          mainClass.class

What is Linux’s native GUI API?

Wayland

As you might hear, wayland is the featured choice of many distros these days, because of its protocol is simpler than the X.

Toolkits of wayland

Toolkits or gui libraries that wayland suggests are:

  • QT 5
  • GTK+
  • LSD
  • Clutter
  • EFL

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

My problem was, that Visual Studio somehow automatically lowercased *ngFor to *ngfor on copy&paste.

Create Django model or update if exists

Thought I'd add an answer since your question title looks like it is asking how to create or update, rather than get or create as described in the question body.

If you did want to create or update an object, the .save() method already has this behaviour by default, from the docs:

Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:

If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.

It's worth noting that when they say 'if the UPDATE didn't update anything' they are essentially referring to the case where the id you gave the object doesn't already exist in the database.

How do I print colored output to the terminal in Python?

You can try this with python 3:

from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

If you are using windows operating system, the above code may not work for you. Then you can try this code:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Hope that helps.

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

"Integer number too large" error message for 600851475143

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".

How to insert &nbsp; in XSLT

When you use the following (without disable-output-escaping!) you'll get a single non-breaking space:

<xsl:text>&#160;</xsl:text>

Hide text using css

See mezzoblue for a nice summary of each technique, with strengths and weaknesses, plus example html and css.

IE9 jQuery AJAX with CORS returns "Access is denied"

Try to use jquery-transport-xdr jQuery plugin for CORS requests in IE8/9.

Authenticating in PHP using LDAP through Active Directory

You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:

  • You must validate input. An empty username/password would pass otherwise.
  • You should ensure the username/password is properly encoded when binding.
  • You should be encrypting the connection using TLS.
  • Using separate LDAP servers for redundancy in case one is down.
  • Getting an informative error message if authentication fails.

It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:

use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;

$domain = (new DomainConfiguration('example.com'))
    ->setUsername('username') # A separate AD service account used by your app
    ->setPassword('password')
    ->setServers(['dc1', 'dc2', 'dc3'])
    ->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);

if (!$ldap->authenticate($username, $password, $message)) {
    echo "Error: $message";
} else {
    // Do something...
}

The authenticate call above will:

  • Validate that neither the username or password is empty.
  • Ensure the username/password is properly encoded (UTF-8 by default)
  • Try an alternate LDAP server in case one is down.
  • Encrypt the authentication request using TLS.
  • Provide additional information if it failed (ie. locked/disabled account, etc)

There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.

Listing all permutations of a string/integer

Slightly modified version in C# that yields needed permutations in an array of ANY type.

    // USAGE: create an array of any type, and call Permutations()
    var vals = new[] {"a", "bb", "ccc"};
    foreach (var v in Permutations(vals))
        Console.WriteLine(string.Join(",", v)); // Print values separated by comma


public static IEnumerable<T[]> Permutations<T>(T[] values, int fromInd = 0)
{
    if (fromInd + 1 == values.Length)
        yield return values;
    else
    {
        foreach (var v in Permutations(values, fromInd + 1))
            yield return v;

        for (var i = fromInd + 1; i < values.Length; i++)
        {
            SwapValues(values, fromInd, i);
            foreach (var v in Permutations(values, fromInd + 1))
                yield return v;
            SwapValues(values, fromInd, i);
        }
    }
}

private static void SwapValues<T>(T[] values, int pos1, int pos2)
{
    if (pos1 != pos2)
    {
        T tmp = values[pos1];
        values[pos1] = values[pos2];
        values[pos2] = tmp;
    }
}

Convert date from String to Date format in Dataframes

Use below function in PySpark to convert datatype into your required datatype. Here I'm converting all the date datatype into the Timestamp column.

def change_dtype(df):
    for name, dtype in df.dtypes:
        if dtype == "date":
            df = df.withColumn(name, col(name).cast('timestamp'))
    return df

Jasmine JavaScript Testing - toBe vs toEqual

For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe and toEqual; either one will work for 5, true, or "the cake is a lie".

To understand the difference between toBe and toEqual, let's imagine three objects.

var a = { bar: 'baz' },
    b = { foo: a },
    c = { foo: a };

Using a strict comparison (===), some things are "the same":

> b.foo.bar === c.foo.bar
true

> b.foo.bar === a.bar
true

> c.foo === b.foo
true

But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.

> b === c
false

Jasmine's toBe matcher is nothing more than a wrapper for a strict equality comparison

expect(c.foo).toBe(b.foo)

is the same thing as

expect(c.foo === b.foo).toBe(true)

Don't just take my word for it; see the source code for toBe.

But b and c represent functionally equivalent objects; they both look like

{ foo: { bar: 'baz' } }

Wouldn't it be great if we could say that b and c are "equal" even if they don't represent the same object?

Enter toEqual, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:

expect(b).not.toBe(c);
expect(b).toEqual(c);

Hope that helps clarify some things.

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

What are the "spec.ts" files generated by Angular CLI for?

if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.

ng new ng-app-name --skip-tests

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

How do I convert a numpy array to (and display) an image?

Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You'll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.

Parsing JSON giving "unexpected token o" error

Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.

var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

How to run C program on Mac OS X using Terminal?

To do this:

  1. open terminal

  2. type in the terminal: nano ; which is a text editor available for the terminal. when you do this. something like this would appear.

  3. here you can type in your C program

  4. type in control(^) + x -> which means to exit.

  5. save the file by typing in y to save the file

  6. write the file name; e.g. helloStack.c (don't forget to add .c)

  7. when this appears, type in gcc helloStack.c

  8. then ./a.out: this should give you your result!!

Find element's index in pandas Series

I'm impressed with all the answers here. This is not a new answer, just an attempt to summarize the timings of all these methods. I considered the case of a series with 25 elements and assumed the general case where the index could contain any values and you want the index value corresponding to the search value which is towards the end of the series.

Here are the speed tests on a 2013 MacBook Pro in Python 3.7 with Pandas version 0.25.3.

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

@Jeff's answer seems to be the fastest - although it doesn't handle duplicates.

Correction: Sorry, I missed one, @Alex Spangher's solution using the list index method is by far the fastest.

Update: Added @EliadL's answer.

Hope this helps.

Amazing that such a simple operation requires such convoluted solutions and many are so slow. Over half a millisecond in some cases to find a value in a series of 25.

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

EXC_BAD_ACCESS signal received

I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before:

startPoint = [[DataPoint alloc] init] ;
startPoint= [DataPointList objectAtIndex: 0];
x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after:

startPoint = [[DataPoint alloc] init] ;
startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS

Thank you so much for your answer. I've been struggling with this problem all day. You're awesome!

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

Reset the Value of a Select Box

This works for me:

$('select').prop('selectedIndex', 0);

FIDDLE

With android studio no jvm found, JAVA_HOME has been set

For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.

I replaced the studio64.exe.vmoptions with the following code.

# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html

-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio

how do you increase the height of an html textbox

I'm assuming from the way you worded the question that you want to change the size after the page has rendered?

In Javascript, you can manipulate DOM CSS properties, for example:

document.getElementById('textboxid').style.height="200px";
document.getElementById('textboxid').style.fontSize="14pt";

If you simply want to specify the height and font size, use CSS or style attributes, e.g.

//in your CSS file or <style> tag
#textboxid
{
    height:200px;
    font-size:14pt;
}

<!--in your HTML-->
<input id="textboxid" ...>

Or

<input style="height:200px;font-size:14pt;" .....>

How can I retrieve Id of inserted entity using Entity framework?

You need to reload the entity after saving changes. Because it has been altered by a database trigger which cannot be tracked by EF. SO we need to reload the entity again from the DB,

db.Entry(MyNewObject).GetDatabaseValues();

Then

int id = myNewObject.Id;

Look at @jayantha answer in below question:

How can I get Id of the inserted entity in Entity framework when using defaultValue?

Looking @christian answer in below question may help too:

Entity Framework Refresh context?

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT *
FROM (
     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub
GROUP BY sub.name

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

Timeout for python requests.get entire response

To create a timeout you can use signals.

The best way to solve this case is probably to

  1. Set an exception as the handler for the alarm signal
  2. Call the alarm signal with a ten second delay
  3. Call the function inside a try-except-finally block.
  4. The except block is reached if the function timed out.
  5. In the finally block you abort the alarm, so it's not singnaled later.

Here is some example code:

import signal
from time import sleep

class TimeoutException(Exception):
    """ Simple Exception to be called on timeouts. """
    pass

def _timeout(signum, frame):
    """ Raise an TimeoutException.

    This is intended for use as a signal handler.
    The signum and frame arguments passed to this are ignored.

    """
    # Raise TimeoutException with system default timeout message
    raise TimeoutException()

# Set the handler for the SIGALRM signal:
signal.signal(signal.SIGALRM, _timeout)
# Send the SIGALRM signal in 10 seconds:
signal.alarm(10)

try:    
    # Do our code:
    print('This will take 11 seconds...')
    sleep(11)
    print('done!')
except TimeoutException:
    print('It timed out!')
finally:
    # Abort the sending of the SIGALRM signal:
    signal.alarm(0)

There are some caveats to this:

  1. It is not threadsafe, signals are always delivered to the main thread, so you can't put this in any other thread.
  2. There is a slight delay after the scheduling of the signal and the execution of the actual code. This means that the example would time out even if it only slept for ten seconds.

But, it's all in the standard python library! Except for the sleep function import it's only one import. If you are going to use timeouts many places You can easily put the TimeoutException, _timeout and the singaling in a function and just call that. Or you can make a decorator and put it on functions, see the answer linked below.

You can also set this up as a "context manager" so you can use it with the with statement:

import signal
class Timeout():
    """ Timeout for use with the `with` statement. """

    class TimeoutException(Exception):
        """ Simple Exception to be called on timeouts. """
        pass

    def _timeout(signum, frame):
        """ Raise an TimeoutException.

        This is intended for use as a signal handler.
        The signum and frame arguments passed to this are ignored.

        """
        raise Timeout.TimeoutException()

    def __init__(self, timeout=10):
        self.timeout = timeout
        signal.signal(signal.SIGALRM, Timeout._timeout)

    def __enter__(self):
        signal.alarm(self.timeout)

    def __exit__(self, exc_type, exc_value, traceback):
        signal.alarm(0)
        return exc_type is Timeout.TimeoutException

# Demonstration:
from time import sleep

print('This is going to take maximum 10 seconds...')
with Timeout(10):
    sleep(15)
    print('No timeout?')
print('Done')

One possible down side with this context manager approach is that you can't know if the code actually timed out or not.

Sources and recommended reading:

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Changing 'java.library.path' variable at runtime is not enough because it is read only once by JVM. You have to reset it like:

System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);

Please, take a loot at: Changing Java Library Path at Runtime.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I was getting the error. I simply added "proxy" in my package.json and the error went away. The error was simply there because the API request was getting made at the same port as the react app was running. You need to provide the proxy so that the API call is made to the port where your backend server is running.

Add JsonArray to JsonObject

I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

How to add property to a class dynamically?

The goal is to create a mock class which behaves like a db resultset.

So what you want is a dictionary where you can spell a['b'] as a.b?

That's easy:

class atdict(dict):
    __getattr__= dict.__getitem__
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

Inconsistent accessibility: property type is less accessible

make your class public access modifier,

just add public keyword infront of your class name

 namespace Test
{
  public  class Delivery
    {
        private string name;
        private string address;
        private DateTime arrivalTime;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public DateTime ArrivlaTime
        {
            get { return arrivalTime; }
            set { arrivalTime = value; }
        }

        public string ToString()
        {
            { return name + address + arrivalTime.ToString(); }
        }
    }
}

Writing Python lists to columns in csv

I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(("list1", "list2"))
    rcount = 0
    for row in list1:
        wr.writerow((list1[rcount], list2[rcount]))
        rcount = rcount + 1
    myfile.close()

header location not working in my php code

just use ob_start(); before include function it will help

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

require_once('../web/a.php');

If this is not working for anyone, following is the good Idea to include file anywhere in the project.

require_once dirname(__FILE__)."/../../includes/enter.php";

This code will get the file from 2 directory outside of the current directory.

How to drop SQL default constraint without knowing its name?

This was the easiest solution that I found.

  • Select Table

  • Press ALT + F1

  • Scroll and view constraint names

Then the query is simple:

ALTER TABLE [Table]
DROP CONSTRAINT [Constraint]

https://www.sqlservergeeks.com/sql-server-dropping-a-primary-key-constraint-in-sql-server-is-it-easy-may-be-may-be-not/

generate random double numbers in c++

something like this:

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
    const long max_rand = 1000000L;
    double x1 = 12.33, x2 = 34.123, x;

    srandom(time(NULL));

    x = x1 + ( x2 - x1) * (random() % max_rand) / max_rand;

    cout << x1 << " <= " << x << " <= " << x2 << endl;

    return 0;
}

Linux: where are environment variables stored?

That variable isn't stored in some script. It's simply set by the X server scripts. You can check the environment variables currently set using set.

Android Room - simple select query - Cannot access database on the main thread

It's not recommended but you can access to database on main thread with allowMainThreadQueries()

MyApp.database =  Room.databaseBuilder(this, AppDatabase::class.java, "MyDatabase").allowMainThreadQueries().build()

Error message "Strict standards: Only variables should be passed by reference"

The second snippet doesn't work either and that's why.

array_shift is a modifier function, that changes its argument. Therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference

Get connection string from App.config

First you have to add System.Configuration reference to your project and then use below code to get connection string.

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();

Pythonic way to combine FOR loop and IF statement

You can use generators too, if generator expressions become too involved or complex:

def gen():
    for x in xyz:
        if x in a:
            yield x

for x in gen():
    print x

How to check if the request is an AJAX request with PHP

This function is using in yii framework for ajax call check.

public function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

How to iterate through a DataTable

DataTable dt = new DataTable();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

adapter.Fill(dt);

foreach(DataRow row in dt.Rows)
{
    TextBox1.Text = row["ImagePath"].ToString();
}

...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

What's the fastest way of checking if a point is inside a polygon in python

Comparison of different methods

I found other methods to check if a point is inside a polygon (here). I tested two of them only (is_inside_sm and is_inside_postgis) and the results were the same as the other methods.

Thanks to @epifanio, I parallelized the codes and compared them with @epifanio and @user3274748 (ray_tracing_numpy) methods. Note that both methods had a bug so I fixed them as shown in their codes below.

One more thing that I found is that the code provided for creating a polygon does not generate a closed path np.linspace(0,2*np.pi,lenpoly)[:-1]. As a result, the codes provided in above GitHub repository may not work properly. So It's better to create a closed path (first and last points should be the same).

Codes

Method 1: parallelpointinpolygon

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):   #<-- Fixed here, must start from zero
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D  

Method 2: ray_tracing_numpy_numba

@jit(nopython=True)
def ray_tracing_numpy_numba(points,poly):
    x,y = points[:,0], points[:,1]
    n = len(poly)
    inside = np.zeros(len(x),np.bool_)
    p2x = 0.0
    p2y = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
        if len(idx):    # <-- Fixed here. If idx is null skip comparisons below.
            if p1y != p2y:
                xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
            if p1x == p2x:
                inside[idx] = ~inside[idx]
            else:
                idxx = idx[x[idx] <= xints]
                inside[idxx] = ~inside[idxx]    

        p1x,p1y = p2x,p2y
    return inside 

Method 3: Matplotlib contains_points

path = mpltPath.Path(polygon,closed=True)  # <-- Very important to mention that the path 
                                           #     is closed (default is false)

Method 4: is_inside_sm (got it from here)

@jit(nopython=True)
def is_inside_sm(polygon, point):
    length = len(polygon)-1
    dy2 = point[1] - polygon[0][1]
    intersections = 0
    ii = 0
    jj = 1

    while ii<length:
        dy  = dy2
        dy2 = point[1] - polygon[jj][1]

        # consider only lines which are not completely above/bellow/right from the point
        if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0] or point[0] >= polygon[jj][0]):

            # non-horizontal line
            if dy<0 or dy2<0:
                F = dy*(polygon[jj][0] - polygon[ii][0])/(dy-dy2) + polygon[ii][0]

                if point[0] > F: # if line is left from the point - the ray moving towards left, will intersect it
                    intersections += 1
                elif point[0] == F: # point on line
                    return 2

            # point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and dx*dx2<=0)
            elif dy2==0 and (point[0]==polygon[jj][0] or (dy==0 and (point[0]-polygon[ii][0])*(point[0]-polygon[jj][0])<=0)):
                return 2

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections & 1  


@njit(parallel=True)
def is_inside_sm_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_sm(polygon,points[i])
    return D  

Method 5: is_inside_postgis (got it from here)

@jit(nopython=True)
def is_inside_postgis(polygon, point):
    length = len(polygon)
    intersections = 0

    dx2 = point[0] - polygon[0][0]
    dy2 = point[1] - polygon[0][1]
    ii = 0
    jj = 1

    while jj<length:
        dx  = dx2
        dy  = dy2
        dx2 = point[0] - polygon[jj][0]
        dy2 = point[1] - polygon[jj][1]

        F =(dx-dx2)*dy - dx*(dy-dy2);
        if 0.0==F and dx*dx2<=0 and dy*dy2<=0:
            return 2;

        if (dy>=0 and dy2<0) or (dy2>=0 and dy<0):
            if F > 0:
                intersections += 1
            elif F < 0:
                intersections -= 1

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections != 0  


@njit(parallel=True)
def is_inside_postgis_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_postgis(polygon,points[i])
    return D  

Benchmark

enter image description here

Timing for 10 million points:

parallelpointinpolygon Elapsed time:      4.0122294425964355
Matplotlib contains_points Elapsed time: 14.117807388305664
ray_tracing_numpy_numba Elapsed time:     7.908452272415161
sm_parallel Elapsed time:                 0.7710440158843994
is_inside_postgis_parallel Elapsed time:  2.131121873855591

Here is the code.

import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from time import time
import numpy as np

np.random.seed(2)

time_parallelpointinpolygon=[]
time_mpltPath=[]
time_ray_tracing_numpy_numba=[]
time_is_inside_sm_parallel=[]
time_is_inside_postgis_parallel=[]
n_points=[]

for i in range(1, 10000002, 1000000): 
    n_points.append(i)
    
    lenpoly = 100
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    N = i
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))
    
    
    #Method 1
    start_time = time()
    inside1=parallelpointinpolygon(points, polygon)
    time_parallelpointinpolygon.append(time()-start_time)

    # Method 2
    start_time = time()
    path = mpltPath.Path(polygon,closed=True)
    inside2 = path.contains_points(points)
    time_mpltPath.append(time()-start_time)

    # Method 3
    start_time = time()
    inside3=ray_tracing_numpy_numba(points,polygon)
    time_ray_tracing_numpy_numba.append(time()-start_time)

    # Method 4
    start_time = time()
    inside4=is_inside_sm_parallel(points,polygon)
    time_is_inside_sm_parallel.append(time()-start_time)

    # Method 5
    start_time = time()
    inside5=is_inside_postgis_parallel(points,polygon)
    time_is_inside_postgis_parallel.append(time()-start_time)


    
plt.plot(n_points,time_parallelpointinpolygon,label='parallelpointinpolygon')
plt.plot(n_points,time_mpltPath,label='mpltPath')
plt.plot(n_points,time_ray_tracing_numpy_numba,label='ray_tracing_numpy_numba')
plt.plot(n_points,time_is_inside_sm_parallel,label='is_inside_sm_parallel')
plt.plot(n_points,time_is_inside_postgis_parallel,label='is_inside_postgis_parallel')
plt.xlabel("N points")
plt.ylabel("time (sec)")
plt.legend(loc = 'best')
plt.show()

CONCLUSION

The fastest algorithms are:

1- is_inside_sm_parallel

2- is_inside_postgis_parallel

3- parallelpointinpolygon (@epifanio)

What is "runtime"?

Runtime basically means when program interacts with the hardware and operating system of a machine. C does not have it's own runtime but instead, it requests runtime from an operating system (which is basically a part of ram) to execute itself.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

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

A convenient way to deal with sizes:

public static class Extensions {
    public static int K(this int value) {
        return value * 1024;
    }
    public static int M(this int value) {
        return value * 1024 * 1024;
    }
}

public class Program {
    public void Main() {
        WSHttpContextBinding serviceMultipleTokenBinding = new WSHttpContextBinding() {
            MaxBufferPoolSize = 2.M(), // instead of 2097152
            MaxReceivedMessageSize = 64.K(), // instead of 65536
        };
    }
}

Check whether a string matches a regex in JS

_x000D_
_x000D_
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
_x000D_
_x000D_

Excel: VLOOKUP that returns true or false?

You could wrap your VLOOKUP() in an IFERROR()

Edit: before Excel 2007, use =IF(ISERROR()...)

How to programmatically determine the current checked out Git branch

adapting the accepted answer to windows powershell:

Split-Path -Leaf (git symbolic-ref HEAD)

What happens if you don't commit a transaction to a database (say, SQL Server)?

When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.

Hibernate SessionFactory vs. JPA EntityManagerFactory

Prefer EntityManagerFactory and EntityManager. They are defined by the JPA standard.

SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager, you can obtain the session by calling:

Session session = entityManager.unwrap(Session.class);

Get the first key name of a JavaScript object

Try this:

for (var firstKey in ahash) break;

alert(firstKey);  // 'one'

Convert unsigned int to signed int C

Since converting unsigned values use to represent positive numbers converting it can be done by setting the most significant bit to 0. Therefore a program will not interpret that as a Two`s complement value. One caveat is that this will lose information for numbers that near max of the unsigned type.

template <typename TUnsigned, typename TSinged>
TSinged UnsignedToSigned(TUnsigned val)
{
    return val & ~(1 << ((sizeof(TUnsigned) * 8) - 1));
}

How do I see active SQL Server connections?

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame
;

See also the Microsoft documentation for sys.sysprocesses.

mysql delete under safe mode

Turning off safe mode in Mysql workbench 6.3.4.0

Edit menu => Preferences => SQL Editor : Other section: click on "Safe updates" ... to uncheck option

Workbench Preferences

List comprehension vs. lambda + filter

Although filter may be the "faster way", the "Pythonic way" would be not to care about such things unless performance is absolutely critical (in which case you wouldn't be using Python!).

SQL Statement with multiple SETs and WHEREs

No. You'll have to do separate updates:

UPDATE  table
SET ID = 111111259
WHERE ID = 2555

UPDATE  table
SET ID = 111111261
WHERE ID = 2724

UPDATE  table
SET ID = 111111263
WHERE ID = 2021

UPDATE  table
SET ID = 111111264
WHERE ID = 2017

How do I catch a PHP fatal (`E_ERROR`) error?

Log fatal errors using the register_shutdown_function, which requires PHP 5.2+:

register_shutdown_function( "fatal_handler" );

function fatal_handler() {
    $errfile = "unknown file";
    $errstr  = "shutdown";
    $errno   = E_CORE_ERROR;
    $errline = 0;

    $error = error_get_last();

    if($error !== NULL) {
        $errno   = $error["type"];
        $errfile = $error["file"];
        $errline = $error["line"];
        $errstr  = $error["message"];

        error_mail(format_error( $errno, $errstr, $errfile, $errline));
    }
}

You will have to define the error_mail and format_error functions. For example:

function format_error( $errno, $errstr, $errfile, $errline ) {
    $trace = print_r( debug_backtrace( false ), true );

    $content = "
    <table>
        <thead><th>Item</th><th>Description</th></thead>
        <tbody>
            <tr>
                <th>Error</th>
                <td><pre>$errstr</pre></td>
            </tr>
            <tr>
                <th>Errno</th>
                <td><pre>$errno</pre></td>
            </tr>
            <tr>
                <th>File</th>
                <td>$errfile</td>
            </tr>
            <tr>
                <th>Line</th>
                <td>$errline</td>
            </tr>
            <tr>
                <th>Trace</th>
                <td><pre>$trace</pre></td>
            </tr>
        </tbody>
    </table>";
    return $content;
}

Use Swift Mailer to write the error_mail function.

See also:

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

How can I list all tags for a Docker image on a remote registry?

If folks want to read tags from the RedHat registry at https://registry.redhat.io/v2 then the steps are:

# example nodejs-12 image
IMAGE_STREAM=nodejs-12
REDHAT_REGISTRY_API="https://registry.redhat.io/v2/rhel8/$IMAGE_STREAM"
# Get an oAuth token based on a service account username and password https://access.redhat.com/articles/3560571
TOKEN=$(curl --silent -u "$REGISTRY_USER":"$REGISTRY_PASSWORD" "https://sso.redhat.com/auth/realms/rhcc/protocol/redhat-docker-v2/auth?service=docker-registry&client_id=curl&scope=repository:rhel:pull" |  jq --raw-output '.token')
# Grab the tags
wget -q --header="Accept: application/json" --header="Authorization: Bearer $TOKEN" -O - "$REDHAT_REGISTRY_API/tags/list" | jq -r '."tags"[]' 

If you want to compare what you have in your local openshift registry against what is in the upstream registry.redhat.com then here is a complete script.

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

How to extract the decision rules from scikit-learn decision-tree?

Here is my approach to extract the decision rules in a form that can be used in directly in sql, so the data can be grouped by node. (Based on the approaches of previous posters.)

The result will be subsequent CASE clauses that can be copied to an sql statement, ex.

SELECT COALESCE(*CASE WHEN <conditions> THEN > <NodeA>*, > *CASE WHEN <conditions> THEN <NodeB>*, > ....)NodeName,* > FROM <table or view>


import numpy as np

import pickle
feature_names=.............
features  = [feature_names[i] for i in range(len(feature_names))]
clf= pickle.loads(trained_model)
impurity=clf.tree_.impurity
importances = clf.feature_importances_
SqlOut=""

#global Conts
global ContsNode
global Path
#Conts=[]#
ContsNode=[]
Path=[]
global Results
Results=[]

def print_decision_tree(tree, feature_names, offset_unit=''    ''):    
    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    value = tree.tree_.value

    if feature_names is None:
        features  = [''f%d''%i for i in tree.tree_.feature]
    else:
        features  = [feature_names[i] for i in tree.tree_.feature]        

    def recurse(left, right, threshold, features, node, depth=0,ParentNode=0,IsElse=0):
        global Conts
        global ContsNode
        global Path
        global Results
        global LeftParents
        LeftParents=[]
        global RightParents
        RightParents=[]
        for i in range(len(left)): # This is just to tell you how to create a list.
            LeftParents.append(-1)
            RightParents.append(-1)
            ContsNode.append("")
            Path.append("")


        for i in range(len(left)): # i is node
            if (left[i]==-1 and right[i]==-1):      
                if LeftParents[i]>=0:
                    if Path[LeftParents[i]]>" ":
                        Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]                                 
                    else:
                        Path[i]=ContsNode[LeftParents[i]]                                   
                if RightParents[i]>=0:
                    if Path[RightParents[i]]>" ":
                        Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]                                   
                    else:
                        Path[i]=" not " +ContsNode[RightParents[i]]                     
                Results.append(" case when  " +Path[i]+"  then ''" +"{:4d}".format(i)+ " "+"{:2.2f}".format(impurity[i])+" "+Path[i][0:180]+"''")

            else:       
                if LeftParents[i]>=0:
                    if Path[LeftParents[i]]>" ":
                        Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]                                 
                    else:
                        Path[i]=ContsNode[LeftParents[i]]                                   
                if RightParents[i]>=0:
                    if Path[RightParents[i]]>" ":
                        Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]                                   
                    else:
                        Path[i]=" not "+ContsNode[RightParents[i]]                      
                if (left[i]!=-1):
                    LeftParents[left[i]]=i
                if (right[i]!=-1):
                    RightParents[right[i]]=i
                ContsNode[i]=   "( "+ features[i] + " <= " + str(threshold[i])   + " ) "

    recurse(left, right, threshold, features, 0,0,0,0)
print_decision_tree(clf,features)
SqlOut=""
for i in range(len(Results)): 
    SqlOut=SqlOut+Results[i]+ " end,"+chr(13)+chr(10)

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

Matplotlib: Specify format of floats for tick labels

In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:

plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)

Check if all values of array are equal

In PHP, there is a solution very simple, one line method :

(count(array_count_values($array)) == 1)

For example :

$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical

That's all.

How to replace a character by a newline in Vim

\r can do the work here for you.

Check if a variable exists in a list in Bash

Prior answers don't use tr which I found to be useful with grep. Assuming that the items in the list are space delimited, to check for an exact match:

echo $mylist | tr ' ' '\n' | grep -F -x -q "$myitem"

This will return exit code 0 if the item is in the list, or exit code 1 if it isn't.

It's best to use it as a function:

_contains () {  # Check if space-separated list $1 contains line $2
  echo "$1" | tr ' ' '\n' | grep -F -x -q "$2"
}

mylist="aa bb cc"

# Positive check
if _contains "${mylist}" "${myitem}"; then
  echo "in list"
fi

# Negative check
if ! _contains "${mylist}" "${myitem}"; then
  echo "not in list"
fi

Virtualenv Command Not Found

I had same problem on Mac OS X El Capitan.

When I installed virtualenv like that sudo pip3 install virtualenv I didn't have virtualenv under my command line.

I solved this problem by following those steps:

  1. Uninstall previous installations.
  2. Switch to super user account prior to virtualenv installation by calling sudo su
  3. Install virtualenv by calling pip3 install virtualenv
  4. Finally you should be able to access virtualenv from both user and super user account.

Java Interfaces/Implementation naming convention

Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:

IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations

The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.

I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Copy all files with a certain extension from all subdirectories

I had a similar problem. I solved it using:

find dir_name '*.mp3' -exec cp -vuni '{}' "../dest_dir" ";"

The '{}' and ";" executes the copy on each file.

Is there a way to specify a max height or width for an image?

set a style for the image

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />

Visually managing MongoDB documents and collections

Here are some popular MongoDB GUI administration tools:

Open source

  • dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.

    dbKoda screenshot

  • Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.

  • adminMongo - web-based or Electron app. Supports server monitoring and document editing.

Closed source

  • NoSQLBoosterfull-featured shell-centric cross-platform GUI tool for MongoDB v2.2-4. Free, Personal, and Commercial editions (feature comparison matrix).
  • MongoDB Compass – provides a graphical user interface that allows you to visualize your schema and perform ad-hoc find queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update queries or access to the shell.
  • Studio 3T, formerly MongoChef – a multi-platform in-place data browser and editor desktop GUI for MongoDB (Core version is free for personal and non-commercial use). Last commit: 2017-Jul-24
  • Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04

  • HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.

  • Database Master – a Windows based MongoDB Management Studio, supports also RDBMS. (not free)
  • SlamData - an open source web-based user-interface that allows you to upload and download data, run queries, build charts, explore data.

Abandoned projects

  • RockMongo – a MongoDB administration tool, written in PHP5. Allegedly the best in the PHP world. Similar to PHPMyAdmin. Last version: 2015-Sept-19
  • Fang of Mongo – a web-based UI built with Django and jQuery. Last commit: 2012-Jan-26, in a forked project.
  • Opricot – a browser-based MongoDB shell written in PHP. Latest version: 2010-Sep-21
  • Futon4Mongo – a clone of the CouchDB Futon web interface for MongoDB. Last commit: 2010-Oct-09
  • MongoVUE – an elegant GUI desktop application for Windows. Free and non-free versions. Latest version: 2014-Jan-20
  • UMongo – a full-featured open-source MongoDB server administration tool for Linux, Windows, Mac; written in Java. Last commit 2014-June
  • Mongo3 – a Ruby/Sinatra-based interface for cluster management. Last commit: Apr 16, 2013

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

Best practice for using assert?

The English language word assert here is used in the sense of swear, affirm, avow. It doesn't mean "check" or "should be". It means that you as a coder are making a sworn statement here:

# I solemnly swear that here I will tell the truth, the whole truth, 
# and nothing but the truth, under pains and penalties of perjury, so help me FSM
assert answer == 42

If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

Install package : Microsoft.AspNet.WebApi.Cors

go to : App_Start --> WebApiConfig

Add :

var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);

Note : If you add '/' as end of the particular url not worked for me.

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

Select row with most recent date per user

 select result from (
     select vorsteuerid as result, count(*) as anzahl from kreditorenrechnung where kundeid = 7148
     group by vorsteuerid
 ) a order by anzahl desc limit 0,1

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

What database does Google use?

As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.

The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.

How do I create executable Java program?

You can use the jar tool bundled with the SDK and create an executable version of the program.

This is how it's done.

I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.

First create your program:

$cat HelloWorldSwing.java
    package start;

    import javax.swing.*;

    public class HelloWorldSwing {
        public static void main(String[] args) {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel label = new JLabel("Hello World");
            frame.add(label);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
    class Dummy {
        // just to have another thing to pack in the jar
    }

Very simple, just displays a window with "Hello World"

Then compile it:

$javac -d . HelloWorldSwing.java

Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.

$ls start/
Dummy.class     HelloWorldSwing.class

Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.

This is the content of my manifest file.

$cat manifest.mf
Main-class: start.HelloWorldSwing

Just describe what the main class is ( the one with the public static void main method )

Once the manifest is ready, the jar executable is invoked.

It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.

$jar -cmf manifest.mf hello.jar start

This creates the .jar file on the system

enter image description here

You can later just double click on that file and it will run as expected.

enter image description here

To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.

Here's a video I've found about: Create a Jar File in Jcreator.

I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.

You can also use jnlp ( Java Network Launcher Protocol ) too.

How to echo (or print) to the js console with php

There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.

The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.

Javascript use variable as object name

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

Essentially, it's using a global variable (attached to the function object)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

How to subtract n days from current date in java?

I found this perfect solution and may useful, You can directly get in format as you want:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -90); // I just want date before 90 days. you can give that you want.

SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); // you can specify your format here...
Log.d("DATE","Date before 90 Days: " + s.format(new Date(cal.getTimeInMillis())));

Thanks.

iPhone viewWillAppear not firing

Thanks iOS 13.

ViewWillDisappear, ViewDidDisappear, ViewWillAppear and ViewDidAppear won't get called on a presenting view controller on iOS 13 which uses a new modal presentation that doesn't cover the whole screen.

Credits are going to Arek Holko. He really saved my day.

enter image description here

PHP JSON String, escape Double Quotes for JS output

I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
    });
    echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

I hope it helps someone/someone improves it.

SQL Call Stored Procedure for each Row without using a cursor

For SQL Server 2005 onwards, you can do this with CROSS APPLY and a table-valued function.

Just for clarity, I'm referring to those cases where the stored procedure can be converted into a table valued function.

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

How can I get my Android device country code without using GPS?

Use the link http://ip-api.com/json. This will provide all the information as JSON. From this JSON content you can get the country easily. This site works using your current IP address. It automatically detects the IP address and sendback details.

Documentation

This is what I got:

{
"as": "AS55410 C48 Okhla Industrial Estate, New Delhi-110020",
"city": "Kochi",
"country": "India",
"countryCode": "IN",
"isp": "Vodafone India",
"lat": 9.9667,
"lon": 76.2333,
"org": "Vodafone India",
"query": "123.63.81.162",
"region": "KL",
"regionName": "Kerala",
"status": "success",
"timezone": "Asia/Kolkata",
"zip": ""
}

N.B. - As this is a third-party API, do not use it as the primary solution. And also I am not sure whether it's free or not.

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

I solved int by updating all the R packages:

update.packages(checkBuilt = TRUE, ask = FALSE)

What is username and password when starting Spring Boot with Tomcat?

If spring-security jars are added in classpath and also if it is spring-boot application all http endpoints will be secured by default security configuration class SecurityAutoConfiguration

This causes a browser pop-up to ask for credentials.

The password changes for each application restarts and can be found in console.

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35

To add your own layer of application security in front of the defaults,

@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

or if you just want to change password you could override default with,

application.xml

security.user.password=new_password

or

application.properties

spring.security.user.name=<>
spring.security.user.password=<>

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

Is it valid to replace http:// with // in a <script src="http://...">?

are there any cases where it doesn't work?

Just to throw this in the mix, if you are developing on a local server, it might not work. You need to specify a scheme, otherwise the browser may assume that src="//cdn.example.com/js_file.js" is src="file://cdn.example.com/js_file.js", which will break since you're not hosting this resource locally.

Microsoft Internet Explorer seem to be particularly sensitive to this, see this question: Not able to load jQuery in Internet Explorer on localhost (WAMP)

You would probably always try to find a solution that works on all your environments with the least amount of modifications needed.

The solution used by HTML5Boilerplate is to have a fallback when the resource is not loaded correctly, but that only works if you incorporate a check:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- If jQuery is not defined, something went wrong and we'll load the local file -->
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

UPDATE: HTML5Boilerplate now uses <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js after deciding to deprecate protocol relative URLs, see [here][3].

C convert floating point to int

Use in C

int C = var_in_float;

They will convert implicit

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

I know it's been three years since this was asked, but I just figured out this problem for myself. I was using into outfile and getting the error. When I commented out this part of the query, it worked.

The FILE privilege is separate from all the others and must be granted to the user running the script.

GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

Remove trailing zeros

I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx), I came up with a neat trick (here as an extension method):

public static decimal Normalize(this decimal value)
{
    return value/1.000000000000000000000000000000000m;
}

The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.

1.200m.Normalize().ToString();

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Try with these commands that have been useful with those errors

path\project\storage\framework\views...

php artisan view:clear

path\project\storage\framework/sessions...

php artisan config:cache

Unicode character for "X" cancel / close?

This is probably pedantry, but so far no one has really given a solution "to create a close button using CSS only." only. Here you go:

#close:before {
  content: "?";
  border: 1px solid gray;
  background-color:#eee;
  padding:0.5em;
  cursor: pointer;
}

http://codepen.io/anon/pen/VaWqYg

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Make sure your email address variable is not blank. Check using

print_r($variable_passed);

Process to convert simple Python script into Windows executable

You can create executable from python script using NSIS (Nullsoft scriptable install system). Follow the below steps to convert your python files to executable.

  • Download and install NSIS in your system.

  • Compress the folder in the .zip file that you want to export into the executable.

  • Start NSIS and select Installer based on ZIP file. Find and provide a path to your compressed file.

  • Provide your Installer Name and Default Folder path and click on Generate to generate your exe file.

  • Once its done you can click on Test to test executable or Close to complete the process.

  • The executable generated can be installed on the system and can be distributed to use this application without even worrying about installing the required python and its packages.

For a video tutorial follow: How to Convert any Python File to .EXE

How can I extract embedded fonts from a PDF as valid font files?

Even though this question is 10 years old, it is still valid and as technology changes so does a valid answer.

In searching the current answers noticed none of them note WOFF (Web Open Font Format) (W3C) (Wikipedia) which can be used to recreate the individual characters (glyphs) and display them in a web page accurately.

Using the free online web page by IDR Solutions, PDF to HTML5 (link), convert a PDF to a zip file. In the resulting zip will be a font directory of woff file types. Current Internet browsers support woff files if you were not aware. (reference) These can be examined at the online site FontDrop! (link).

WOFF files can be converted to/from OTF or TTF at WOFFer – WOFF font converter

Also the zip file from PDF to HTML5 will contain an HTML file for each page of the PDF that can be opened in an Internet browser and is one of the best and most accurate PDF translations I have found or seen.

While I am just learning how to use WOFF files, this is worth passing along. Enjoy.

PS, I will probably update with more info as I learn more about using woff file types, but as this is creative commons, feel free to edit this answer if you have something of value to pass along.