Programs & Examples On #Positioning

This tag is ambiguous. DO NOT USE THIS TAG. - Please use (or create, if appropriate) other, more specific tags.

Stopping fixed position scrolling at a certain point?

I loved @james answer but I was looking for its inverse i.e. stop fixed position right before footer, here is what I came up with

var $fixed_element = $(".some_element")
if($fixed_element.length){
        var $offset = $(".footer").position().top,
            $wh = $(window).innerHeight(),
            $diff = $offset - $wh,
            $scrolled = $(window).scrollTop();
        $fixed_element.css("bottom", Math.max(0, $scrolled-$diff));
    }

So now the fixed element would stop right before footer. and will not overlap with it.

How can I fill a div with an image while keeping it proportional?

The only way I achieved the "best case" scenario described, was putting the image as a background:

<div class="container"></div>?
.container {
    width: 150px;
    height: 100px;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}?

CSS: fixed to bottom and centered

The problem lies in position: static. Static means don't do anyting at all with the position. position: absolute is what you want. Centering the element is still tricky though. The following should work:

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 0px;
  right: 0px;
}

or

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 50%;
  transform: translate(-50%, 0);
}

But I recommend the first method. I used centering techniques from this answer: How to center absolutely positioned element in div?

Make div stay at bottom of page's content all the time even when there are scrollbars

I've solved a similar issue by putting all of my main content within an extra div tag (id="outer"). I've then moved the div tag with id="footer" outside of this last "outer" div tag. I've used CSS to specify the height of "outer" and specified the width and height of "footer". I've also used CSS to specify the margin-left and margin-right of "footer" as auto. The result is that the footer sits firmly at the bottom of my page and scrolls with the page too (although, it's still appears inside the "outer" div, but happily outside of the main "content" div. which seems strange, but it's where I want it).

How to position the div popup dialog to the center of browser screen?

I think you need to make the .holder position:relative; and .popup position:absolute;

How to make a HTML list appear horizontally instead of vertically using CSS only?

quite simple:

ul.yourlist li { float:left; }

or

ul.yourlist li { display:inline; }

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I cheated problem using transition by steps, not smoothly

transition-timing-function: steps(10, end);

It is not a solving, it is a cheating and can not be applied everywhere.

I can't explain it, but it works for me. None of another answers helps me (OSX, Chrome 63, Non-Retina display).

https://jsfiddle.net/tuzae6a9/6/

How do I center an SVG in a div?

SVG is inline by default. Add display: block to it and then margin: auto will work as expected.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});

This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).

How to position absolute inside a div?

  1. First all block level elements are postioned static to the 'document'. The default positioning for all elements is position: static, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.
  2. Relative position: If you specify position: relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.
  3. When you specify position: absolute, the element is removed from the document and placed exactly where you tell it to go.

So in regard to your question you should position the containing block relative, i.e:

#parent {
  position: relative;
}

And the child element you should position absolute to the parent element like this:

#child {
  position: absolute;
}

See: Learn CSS Positioning in Ten Steps

How to center an image horizontally and align it to the bottom of the container?

This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.

If the image is alone in the div, then I recommend something like this:

.image_block {
    width: 175px;
    height: 175px;
    line-height: 175px;
    text-align: center;
    vertical-align: bottom;
}

You may need to stick the vertical-align call on the image instead; not really sure without testing it. Using vertical-align and line-height is going to treat you a lot better, though, than trying to mess around with absolute positioning.

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

Position an element relative to its container

If you need to position an element relative to its containing element first you need to add position: relative to the container element. The child element you want to position relatively to the parent has to have position: absolute. The way that absolute positioning works is that it is done relative to the first relatively (or absolutely) positioned parent element. In case there is no relatively positioned parent, the element will be positioned relative to the root element (directly to the HTML element).

So if you want to position your child element to the top left of the parent container, you should do this:

.parent {
  position: relative;
} 

.child {
  position: absolute;
  top: 0;
  left: 0;  
}

You will benefit greatly from reading this article. Hope this helps!

How to horizontally center a floating element of a variable width?

This works better when the id = container (which is the outer div) and id = contained (which is the inner div). The problem with the highly recommended solution is that it results in some cases into an horizontal scrolling bar when the browser is trying to cater for the left: -50% attribute. There is a good reference for this solution

        #container {
            text-align: center;
        }
        #contained {
            text-align: left;
            display: inline-block;
        }

How can I make a div stick to the top of the screen once it's been scrolled to?

I came across this when searching for the same thing. I know it's an old question but I thought I'd offer a more recent answer.

Scrollorama has a 'pin it' feature which is just what I was looking for.

http://johnpolacek.github.io/scrollorama/

CSS position:fixed inside a positioned element

If your close button is going to be text, this works very well for me:

#close {
  position: fixed;
  width: 70%; /* the width of the parent */
  text-align: right;
}
#close span {
  cursor: pointer;
}

Then your HTML can just be:

<div id="close"><span id="x">X</span></div>

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

sizing div based on window width

A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.

grid controls for ASP.NET MVC?

We have been using jqGrid on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje.

Detect enter press in JTextField

First add action command on JButton or JTextField by:

JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");

Then add ActionListener to both JTextField and JButton.

JButton.addActionListener(listener);
JTextField.addActionListener(listener);

After that, On you ActionListener implementation write

@Override
public void actionPerformed(ActionEvent e)
{
    String actionCommand = e.getActionCommand();

    if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your   actionCommand for press Enter"))
    {
        //Do something
    }
}

What does PermGen actually stand for?

Permanent Generation. See the java GC tuning guide for more details on the garbage collector.

How do I run PHP code when a user clicks on a link?

Yeah, you'd need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won't be redirected in the browser. You could use the following in jQuery, if that's acceptable for your project:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
    $.get("somepage.php");
    return false;
}
</script>

<a href="#" onclick="doSomething();">Click Me!</a>

You could also do a post-back if you need to use form values (use the $.post() method).

How to convert any date format to yyyy-MM-dd

You will need to parse the input to a DateTime object and then convert it to any text format you want.

If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.

Unclosed Character Literal error

String y = "hello";

would work (note the double quotes).

char y = 'h'; this will work for chars (note the single quotes)

but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

Purpose of #!/usr/bin/python3 shebang

  1. And this line is how.

  2. It is ignored.

  3. It will fail to run, and should be changed to point to the proper location. Or env should be used.

  4. It will fail to run, and probably fail to run under a different version regardless.

Error: Argument is not a function, got undefined

Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.

Bootstrap DatePicker, how to set the start date for tomorrow?

this.$('#datepicker').datepicker({minDate: 1});

minDate:0 - Enable dates in the calender from the current date. MinDate:1 enable dates in the calender currentDate+1

To Restrict date between from tomorrow and the same day next month u need to give something like

$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });

How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

How do I access nested HashMaps in Java?

You can get the nested value by repeating .get(), but with deeply nested maps you have to do a lot of casting into Map. An easier way is to use a generic method for getting a nested value.

Implementation

public static <T> T getNestedValue(Map map, String... keys) {
    Object value = map;

    for (String key : keys) {
        value = ((Map) value).get(key);
    }

    return (T) value;
}

Usage

// Map contents with string and even a list:
{
  "data": {
    "vehicles": {
      "list": [
        {
          "registration": {
            "owner": {
              "id": "3643619"
            }
          }
        }
      ]
    }
  }
}
List<Map> list = getNestedValue(mapContents, "data", "vehicles", "list");
Map first = list.get(0);
String id = getNestedValue(first, "registration", "owner", "id");

mysql: SOURCE error 2?

I was having this issue and it turns out if you are using wamp server to run mysql, you have to use the file path within the wamp64 folder. So when the absolute path is: C:/wamp64/www/foldername/filename.sql The path you have to use is: www/foldername/filename.sql

Split string and get first value only

Actually, there is a better way to do it than split:

public string GetFirstFromSplit(string input, char delimiter)
{
    var i = input.IndexOf(delimiter);

    return i == -1 ? input : input.Substring(0, i);
}

And as extension methods:

public static string FirstFromSplit(this string source, char delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

public static string FirstFromSplit(this string source, string delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

Usage:

string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"

Writing an input integer into a cell

I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.

So

Range("RefNo") = InputBox("....") 

is safer than

Range("H1") = InputBox("....") 

You can set the value of several cells, too.

Range("Results").Resize(10,3) = arrResults()

where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this

Option Base 1

at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).

strdup() - what does it do in C?

No point repeating the other answers, but please note that strdup() can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

CKEditor instance already exists

Perhaps this will help you out - I've done something similar using jquery, except I'm loading up an unknown number of ckeditor objects. It took my a while to stumble onto this - it's not clear in the documentation.

function loadEditors() {
    var $editors = $("textarea.ckeditor");
    if ($editors.length) {
        $editors.each(function() {
            var editorID = $(this).attr("id");
            var instance = CKEDITOR.instances[editorID];
            if (instance) { instance.destroy(true); }
            CKEDITOR.replace(editorID);
        });
    }
}

And here is what I run to get the content from the editors:

    var $editors = $("textarea.ckeditor");
    if ($editors.length) {
        $editors.each(function() {
            var instance = CKEDITOR.instances[$(this).attr("id")];
            if (instance) { $(this).val(instance.getData()); }
        });
    }

UPDATE: I've changed my answer to use the correct method - which is .destroy(). .remove() is meant to be internal, and was improperly documented at one point.

Convert DataTable to List<T>

you can convert your datatable to list. check the following link

https://stackoverflow.com/a/35171050/1805776

public static class Helper
{
    public static List<T> DataTableToList<T>(this DataTable dataTable) where T : new()
    {
        var dataList = new List<T>();

        //Define what attributes to be read from the class
        const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;

        //Read Attribute Names and Types
        var objFieldNames = typeof(T).GetProperties(flags).Cast<System.Reflection.PropertyInfo>().
            Select(item => new
            {
                Name = item.Name,
                Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
            }).ToList();

        //Read Datatable column names and types
        var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
            Select(item => new
            {
                Name = item.ColumnName,
                Type = item.DataType
            }).ToList();

        foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
        {
            var classObj = new T();

            foreach (var dtField in dtlFieldNames)
            {
                System.Reflection.PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);

                var field = objFieldNames.Find(x => x.Name == dtField.Name);

                if (field != null)
                {

                    if (propertyInfos.PropertyType == typeof(DateTime))
                    {
                        propertyInfos.SetValue
                        (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(Nullable<DateTime>))
                    {
                        propertyInfos.SetValue
                        (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(int))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToInt(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(long))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToLong(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(decimal))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(String))
                    {
                        if (dataRow[dtField.Name].GetType() == typeof(DateTime))
                        {
                            propertyInfos.SetValue
                            (classObj, ConvertToDateString(dataRow[dtField.Name]), null);
                        }
                        else
                        {
                            propertyInfos.SetValue
                            (classObj, ConvertToString(dataRow[dtField.Name]), null);
                        }
                    }
                    else
                    {

                        propertyInfos.SetValue
                            (classObj, Convert.ChangeType(dataRow[dtField.Name], propertyInfos.PropertyType), null);

                    }
                }
            }
            dataList.Add(classObj);
        }
        return dataList;
    }

    private static string ConvertToDateString(object date)
    {
        if (date == null)
            return string.Empty;

        return date == null ? string.Empty : Convert.ToDateTime(date).ConvertDate();
    }

    private static string ConvertToString(object value)
    {
        return Convert.ToString(ReturnEmptyIfNull(value));
    }

    private static int ConvertToInt(object value)
    {
        return Convert.ToInt32(ReturnZeroIfNull(value));
    }

    private static long ConvertToLong(object value)
    {
        return Convert.ToInt64(ReturnZeroIfNull(value));
    }

    private static decimal ConvertToDecimal(object value)
    {
        return Convert.ToDecimal(ReturnZeroIfNull(value));
    }

    private static DateTime convertToDateTime(object date)
    {
        return Convert.ToDateTime(ReturnDateTimeMinIfNull(date));
    }

    public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
    {
        if (datetTime != DateTime.MinValue)
        {
            if (excludeHoursAndMinutes)
                return datetTime.ToString("yyyy-MM-dd");
            return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }
        return null;
    }
    public static object ReturnEmptyIfNull(this object value)
    {
        if (value == DBNull.Value)
            return string.Empty;
        if (value == null)
            return string.Empty;
        return value;
    }
    public static object ReturnZeroIfNull(this object value)
    {
        if (value == DBNull.Value)
            return 0;
        if (value == null)
            return 0;
        return value;
    }
    public static object ReturnDateTimeMinIfNull(this object value)
    {
        if (value == DBNull.Value)
            return DateTime.MinValue;
        if (value == null)
            return DateTime.MinValue;
        return value;
    }
}

Going from MM/DD/YYYY to DD-MMM-YYYY in java

Try this,

Date currDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = dateFormat.format(currDate);
System.out.println("strCurrDate->"+strCurrDate);

Use dynamic variable names in JavaScript

Although this have an accepted answer I would like to add an observation:

In ES6 using let doesn't work:

_x000D_
_x000D_
/*this is NOT working*/_x000D_
let t = "skyBlue",_x000D_
    m = "gold",_x000D_
    b = "tomato";_x000D_
_x000D_
let color = window["b"];_x000D_
console.log(color);
_x000D_
_x000D_
_x000D_

However using var works

_x000D_
_x000D_
/*this IS working*/_x000D_
var t = "skyBlue",_x000D_
    m = "gold",_x000D_
    b = "tomato";_x000D_
_x000D_
let color = window["b"];_x000D_
console.log(color);
_x000D_
_x000D_
_x000D_

I hope this may be useful to some.

error C2065: 'cout' : undeclared identifier

is normally stored in the C:\Program Files\Microsoft Visual Studio 8\VC\include folder. First check if it is still there. Then choose Tools + Options, Projects and Solutions, VC++ Directories, choose "Include files" in the "Show Directories for" combobox and double-check that $(VCInstallDir)include is on top of the list.

Changing cursor to waiting in javascript/jquery

Setting the cursor for 'body' will change the cursor for the background of the page but not for controls on it. For example, buttons will still have the regular cursor when hovering over them. The following is what I am using:

To set the 'wait' cursor, create a style element and insert in the head:

var css = "* { cursor: wait; !important}";
var style = document.createElement("style");
style.type = "text/css";
style.id = "mywaitcursorstyle";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);

Then to restore the cursor, delete the style element:

var style = document.getElementById("mywaitcursorstyle");
if (style) {
  style.parentNode.removeChild(style);
}

How to make a list of n numbers in Python and randomly select any number?

After that I would like to select another number from the remaining numbers of the list (N-1) and then use that also.

Then you arguably do not really want to create a list of numbers from 1 to N just for the purpose of picking one (why not just ask for a random number in that range directly, instead of explicitly creating it to choose from?), but instead to shuffle such a list. Fortunately, the random module has you covered for this, too: just use random.shuffle.

Of course, if you have a huge list of numbers and you only want to draw a few, then it certainly makes sense to draw each using random.choice and remove it.

But... why do you want to select numbers from a range, that corresponds to the count of some items? Are you going to use the number to select one of the items? Don't do that; that's going out of your way to make things too complicated. If you want to select one of the items, then do so directly - again with random.choice.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

Adding POST parameters before submit

To add that using Jquery:

$('#commentForm').submit(function(){ //listen for submit event
    $.each(params, function(i,param){
        $('<input />').attr('type', 'hidden')
            .attr('name', param.name)
            .attr('value', param.value)
            .appendTo('#commentForm');
    });

    return true;
}); 

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

Removing Java 8 JDK from Mac

I was able to unistall jdk 8 in mavericks successfully doing the following steps:

Run this command to just remove the JDK

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk<version>.jdk

Run these commands if you want to remove plugins

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

Laravel back button

Laravel 5.2+, back button

<a href="{{ url()->previous() }}" class="btn btn-default">Back</a>

How to import cv2 in python3?

Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

git stash changes apply to new branch?

Since you've already stashed your changes, all you need is this one-liner:

  • git stash branch <branchname> [<stash>]

From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

How to setup Tomcat server in Netbeans?

While installing Netbeans itself, you will get an option which servers needs to be installed and integrated with Netbeans. First screen itself will show.

Another option is to reinstall Netbeans by closing all the open projects.

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

concatenate char array in C

asprintf is not 100% standard, but it's available via the GNU and BSD standard C libraries, so you probably have it. It allocates the output, so you don't have to sit there and count characters.

char *hi="Hello";
char *ext = ".txt";
char *cat;

asprintf(&cat, "%s%s", hi, ext);

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

Ajax using https on an http page

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

How to initialize weights in PyTorch?

Here is the better way, just pass your whole model

import torch.nn as nn
def initialize_weights(model):
    # Initializes weights according to the DCGAN paper
    for m in model.modules():
        if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):
            nn.init.normal_(m.weight.data, 0.0, 0.02)
        # if you also want for linear layers ,add one more elif condition 

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

Node.js Error: Cannot find module express

1.first check if express is install at correct location. 2. npm install express (run this command). 3. express will save under your "node_modules" folder

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

for cordova developers having this issue

try to set

<preference name="deployment-target" value="8.0" />

in confix.xml

SQL how to check that two tables has exactly the same data?

Enhancement to dietbuddha's answer...

select * from
(
    select * from tableA
    minus
    select * from tableB
)
union all
select * from
(
    select * from tableB
    minus
    select * from tableA
)

What is %timeit in python?

I would just like to add another useful advantage of using %timeit to answer by mu ? that:

  • You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit to built the variable that is built in an another enviroment that timeit works.

PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.

Adding an identity to an existing column

Basically there are four logical steps.

  1. Create a new Identity column. Turn on Insert Identity for this new column.

  2. Insert the data from the source column (the column you wished to convert to Identity) to this new column.

  3. Turn off the Insert Identity for the new column.

  4. Drop your source column & rename the new column to the name of the source column.

There may be some more complexities like working across multiple servers etc.

Please refer the following article for the steps (using ssms & T-sql). These steps are intended for beginners with less grip on T-SQL.

http://social.technet.microsoft.com/wiki/contents/articles/23816.how-to-convert-int-column-to-identity-in-the-ms-sql-server.aspx

Open directory dialog

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gearplay
{
    /// <summary>
    /// ?????? ?????????????? ??? OpenFolderBrows.xaml
    /// </summary>
    public partial class OpenFolderBrows : Page
    {
        internal string SelectedFolderPath { get; set; }
        public OpenFolderBrows()
        {
            InitializeComponent();
            Selectedpath();
            InputLogicalPathCollection();
             
        }

        internal void Selectedpath()
        {
            Browser.Navigate(@"C:\");
            
            Browser.Navigated += Browser_Navigated;
        }

        private void Browser_Navigated(object sender, NavigationEventArgs e)
        {
            SelectedFolderPath = e.Uri.AbsolutePath.ToString();
            //MessageBox.Show(SelectedFolderPath);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
          
           
        }
        
        string [] testing { get; set; }
        private void InputLogicalPathCollection()
        {            // add Menu items for Cotrol 
            string[] DirectoryCollection_Path = Environment.GetLogicalDrives(); // Get Local Drives
            testing = new string[DirectoryCollection_Path.Length];
            //MessageBox.Show(DirectoryCollection_Path[0].ToString());
            MenuItem[]  menuItems = new MenuItem[DirectoryCollection_Path.Length]; // Create Empty Collection
            for(int i=0;i<menuItems.Length;i++)
            {
                // Create collection depend how much logical drives 
                menuItems[i] = new MenuItem();
                menuItems[i].Header = DirectoryCollection_Path[i];
                menuItems[i].Name = DirectoryCollection_Path[i].Substring(0,DirectoryCollection_Path.Length-1);
                DirectoryCollection.Items.Add(menuItems[i]);
                menuItems[i].Click += OpenFolderBrows_Click;
                testing[i]= DirectoryCollection_Path[i].Substring(0, DirectoryCollection_Path.Length - 1);
            }

            

        }
        
        private void OpenFolderBrows_Click(object sender, RoutedEventArgs e)
        {

            foreach (string str in testing)
            {
                if (e.OriginalSource.ToString().Contains("Header:"+str)) // Navigate to Local drive
                {
                    Browser.Navigate(str + @":\");
                   
                }


            }


        }

        private void Goback_Click(object sender, RoutedEventArgs e)
        {// Go Back
            try
            {
                Browser.GoBack();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Goforward_Click(object sender, RoutedEventArgs e)
        { //Go Forward
            try
            {
                Browser.GoForward();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FolderForSave_Click(object sender, RoutedEventArgs e)
        {
            // Separate Click For Go Back same As Close App With send string var to Main Window ( Main class etc.) 
            this.NavigationService.GoBack();
        }
    }
}

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

What I needed: A document number with a fixed number of integers that would also act like an AutoField.

My searches took me all over incl. this page.

Finally I did something like this:

I created a table with a DocuNumber field as an IntegerField with foll. attributes:

  • max_length=6
  • primary_key=True
  • unique=True
  • default=100000

The max_length value anything as required (and thus the corresponding default= value).

A warning is issued while creating the said model, which I could ignore.

Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.

Afterwards changed the model key field as:

  • Changed the field type as: AutoField
  • Got rid of the max_length And defaultattributes
  • Retained the primary_key = True attribute

The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.

So far so good.

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

error: request for member '..' in '..' which is of non-class type

Parenthesis is not required to instantiate a class object when you don't intend to use a parameterised constructor.

Just use Foo foo2;

It will work.

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1



class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1



class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

How to print pthread_t

As James mentioned above, the best way is to look at the header where the type is defined.

You can find the definition of pthread_t in pthreadtypes.h which can be found at:

/usr/include/bits/pthreadtypes.h

best way to get the key of a key/value javascript object

for showing as a string, simply use:

console.log("they are: " + JSON.stringify(foo));

Best way to remove an event handler in jQuery?

Hope my below code explains all. HTML:

_x000D_
_x000D_
(function($){_x000D_
_x000D_
     $("#btn_add").on("click",function(){_x000D_
       $("#btn_click").on("click",added_handler);_x000D_
       alert("Added new handler to button 1");_x000D_
     });_x000D_
_x000D_
  _x000D_
 _x000D_
     $("#btn_remove").on("click",function(){_x000D_
       $("#btn_click").off("click",added_handler);_x000D_
       alert("Removed new handler to button 1");_x000D_
     });_x000D_
_x000D_
  _x000D_
   function fixed_handler(){_x000D_
    alert("Fixed handler");_x000D_
  }_x000D_
  _x000D_
   function added_handler(){_x000D_
    alert("new handler");_x000D_
  }_x000D_
  _x000D_
  $("#btn_click").on("click",fixed_handler);_x000D_
  $("#btn_fixed").on("click",fixed_handler);_x000D_
  _x000D_
  _x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btn_click">Button 1</button>_x000D_
  <button id="btn_add">Add Handler</button>_x000D_
  <button id="btn_remove">Remove Handler</button>_x000D_
  <button id="btn_fixed">Fixed Handler</button>
_x000D_
_x000D_
_x000D_

Hibernate vs JPA vs JDO - pros and cons of each?

I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is: https://github.com/TorbenVesterager/BadAssWebApp

Okay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)

PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)

How to send a POST request with BODY in swift

Accepted answer in Xcode 11 - Swift 5 - Alamofire 5.0

func postRequest() {
    let parameters: [String: Any] = [
        "IdQuiz" : 102,
        "IdUser" : "iosclient",
        "User" : "iosclient",
        "List": [
            [
                "IdQuestion" : 5,
                "IdProposition": 2,
                "Time" : 32
            ],
            [
                "IdQuestion" : 4,
                "IdProposition": 3,
                "Time" : 9
            ]
        ]
    ]
    AF.request("http://myserver.com", method:.post, parameters: parameters,encoding: JSONEncoding.default) .responseJSON { (response) in
        print(response)
    }
}

axios post request to send form data

Upload (multiple) binary files

Node.js

Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:

const FormData = require('form-data')
const fs = require('fs')
const path = require('path')

const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
  headers: formData.getHeaders()
})
  • Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
  • I use async and await above, you can change them to plain Promise statements if you don't like them
  • In order to add your own headers, you just headers: { ...yourHeaders, ...formData.getHeaders() }

Newly added content below:

Browser

Browser's FormData is different from the NPM package 'form-data'. The following code works for me in browser:

HTML:

<input type="file" id="image" accept="image/png"/>

JavaScript:

const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)

Change background color for selected ListBox item

You have to create a new template for item selection like this.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                Padding="{TemplateBinding Control.Padding}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True">
                <ContentPresenter
                    Content="{TemplateBinding ContentControl.Content}"
                    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                    HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                    VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                    SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Django datetime issues (default=datetime.now())

Instead of using datetime.now you should be really using from django.utils.timezone import now

Reference:

so go for something like this:

from django.utils.timezone import now


created_date = models.DateTimeField(default=now, editable=False)

Date difference in years using C#

It's unclear how you want to handle fractional years, but perhaps like this:

DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

The problem is that SQL 2008 MS has a bug where connecting to a remote server (say like a service provider collocation) it will always try to open the fist db in the list, and since the possibilities of been ur db the first on the list are really low, it will throw and error and fail to display the list of dbs... which using sql 2005 management studio it just works.

Wished I could use SQL 2008 MS, but looks like as far I connect to remote SQL 2005, SQL 2008 is out of the question on my dev machine :(

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

Simultaneously merge multiple data.frames in a list

You can use recursion to do this. I haven't verified the following, but it should give you the right idea:

MergeListOfDf = function( data , ... )
{
    if ( length( data ) == 2 ) 
    {
        return( merge( data[[ 1 ]] , data[[ 2 ]] , ... ) )
    }    
    return( merge( MergeListOfDf( data[ -1 ] , ... ) , data[[ 1 ]] , ... ) )
}

Detect home button press in android

Try to create a counter for each screen. If the user touch HOME, then the counter will be zero.

public void onStart() {
  super.onStart();
  counter++;
}

public void onStop() {
  super.onStop();
  counter--;    
  if (counter == 0) {
      // Do..
  }
}

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Validate fields after user has left a field

From version 1.3.0 this can easily be done with $touched, which is true after the user has left the field.

<p ng-show="form.field.$touched && form.field.$invalid">Error</p>

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

Git Push Error: insufficient permission for adding an object to repository database

I was getting this problem with a remote repository on a Samba share; I pulled successfully from this remote, but failed when pushing to it.

The cause of the error was incorrect credentials in my ~/.smbcredentials file.

regex.test V.S. string.match to know if a string matches a regular expression

This is my benchmark results benchmark results

test 4,267,740 ops/sec ±1.32% (60 runs sampled)

exec 3,649,719 ops/sec ±2.51% (60 runs sampled)

match 3,623,125 ops/sec ±1.85% (62 runs sampled)

indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)

test method is faster than the match method, but the fastest method is the indexOf

Test if a variable is a list or tuple

Has to be more complex test if you really want to handle just about anything as function argument.

type(a) != type('') and hasattr(a, "__iter__")

Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('').

Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

Understanding typedefs for function pointers in C

cdecl is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.

As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:

typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);

rather than:

typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);

cdecl can help you out with this stuff:

cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )

And is (in fact) exactly how I generated that crazy mess above.

Basic example of using .ajax() with JSONP?

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.


NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP):

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

delete a column with awk or sed

It seems you could simply go with

awk '{print $1 " " $2}' file

This prints the two first fields of each line in your input file, separated with a space.

.gitignore is ignored by Git

Even if you haven't tracked the files so far, Git seems to be able to "know" about them even after you add them to .gitignore.

WARNING: First commit or stash your current changes, or you will lose them.

Then run the following commands from the top folder of your Git repository:

git rm -r --cached .
git add .
git commit -m "fixed untracked files"

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);

jQuery click not working for dynamically created items

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

EditText, clear focus on touch outside

This simple snippet of code does what you want

GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                KeyboardUtil.hideKeyboard(getActivity());
                return true;
            }
        });
mScrollView.setOnTouchListener((v, e) -> gestureDetector.onTouchEvent(e));

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms

The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.

The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.

The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.

angular.js ng-repeat li items with html content

You can use NGBindHTML or NGbindHtmlUnsafe this will not escape the html content of your model.

http://jsfiddle.net/n9rQr/

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts"  ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

This works, anyway you should be very careful when using unsanitized html content, you should really trust the source of the content.

android - setting LayoutParams programmatically

Just replace from bottom and add this

tv.setLayoutParams(new ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT));

before

llview.addView(tv);

How to center a navigation bar with CSS or HTML?

Your nav div is actually centered correctly. But the ul inside is not. Give the ul a specific width and center that as well.

Convert file: Uri to File in Android

For this case, especially on Android, the way going for bytes is usually faster.

With this, I solved it by setting up a class FileHelper which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class UriHelper which is given the responsibility to figure out path of Uri and permission.

As far as it's knew generally, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset) can help us to transfer string you want to bytes you need.

How to let UriHelper and FileHelper you to copy a picture noted by Uri into a file, you can run:

FileHelper.getInstance().copy(UriHelper.getInstance().toFile(uri_of_a_picture)
                        , FileHelper.getInstance().createExternalFile(null, UriHelper.getInstance().generateFileNameBasedOnTimeStamp()
                                + UriHelper.getInstance().getFileName(uri_of_a_picture, context), context)
                );

about my UriHelper:

public class UriHelper {
private static UriHelper INSTANCE = new UriHelper();

public static UriHelper getInstance() {
    return INSTANCE;
}

@SuppressLint("SimpleDateFormat")
public String generateFileNameBasedOnTimeStamp() {
    return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

/**
 * if uri.getScheme.equals("content"), open it with a content resolver.
 * if the uri.Scheme.equals("file"), open it using normal file methods.
 */
//

public File toFile(Uri uri) {
    if (uri == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    return new File(uri.getPath());
}

public DocumentFile toDocumentFile(Uri uri) {
    if (uri == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    return DocumentFile.fromFile(new File(uri.getPath()));
}

public Uri toUri(File file) {
    if (file == null) return null;
    Logger.d(">>> file path:" + file.getAbsolutePath());
    return Uri.fromFile(file); //returns an immutable URI reference representing the file
}

public String getPath(Uri uri, Context context) {
    if (uri == null) return null;
    if (uri.getScheme() == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    String path;
    if (uri.getScheme().equals("content")) {
        //Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            Logger.e("!!! cursor is null");
            return null;
        }
        if (cursor.getCount() >= 0) {
            Logger.d("... the numbers of rows:" + cursor.getCount()
                        + "and the numbers of columns:" + cursor.getColumnCount());
            if (cursor.isBeforeFirst()) {
                while (cursor.moveToNext()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                }
            } else {
                cursor.moveToFirst();
                do {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                } while (cursor.moveToNext());
            }
            path = uri.getPath();
            cursor.close();
            Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
            return path;
        } else {
            path = uri.getPath();
            Logger.d("... content scheme:" + uri.getScheme()
                    + " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
                    + "  and return:" + path);
            return path;
        }
    } else {
        path = uri.getPath();
        Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
        return path;
    }
}

public String getFileName(Uri uri, Context context) {
    if (uri == null) return null;
    if (uri.getScheme() == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    String path;
    if (uri.getScheme().equals("content")) {
        //Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            Logger.e("!!! cursor is null");
            return null;
        }
        if (cursor.getCount() >= 0) {
            Logger.d("... the numbers of rows:" + cursor.getCount()
                    + "and the numbers of columns:" + cursor.getColumnCount());
            if (cursor.isBeforeFirst()) {
                while (cursor.moveToNext()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                }
            } else {
                cursor.moveToFirst();
                do {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                } while (cursor.moveToNext());
            }
            cursor.moveToFirst();
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
            cursor.close();
            Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
            return path;
        } else {
            path = uri.getLastPathSegment();
            Logger.d("... content scheme:" + uri.getScheme()
                    + " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
                    + "  and return:" + path);
            return path;
        }
    } else {
        path = uri.getLastPathSegment();
        Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
        return path;
    }
}

}

about my FileHelper:

public class FileHelper {
private static final String DEFAULT_DIR_NAME = "AmoFromTaiwan";
private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final int EOF = -1;
private static FileHelper INSTANCE = new FileHelper();

public static FileHelper getInstance() {
    return INSTANCE;
}

private boolean isExternalStorageWritable(Context context) {
    /*
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state);
    */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            Logger.e("!!! checkSelfPermission() not granted");
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

private boolean isExternalStorageReadable(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            Logger.e("!!! checkSelfPermission() not granted");
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

@SuppressLint("SimpleDateFormat")
private String generateFileNameBasedOnTimeStamp() {
    return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

public File createExternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File dir ;
    File file;
    if (!isExternalStorageWritable(context)) {
        Logger.e("!!! external storage not writable");
        return null;
    }
    if (dir_name == null) {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
    } else {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
    }
    Logger.d("... going to access an external dir:" + dir_path);
    dir = new File(dir_path);
    if (!dir.exists()) {
        Logger.d("... going to mkdirs:" + dir_path);
        if (!dir.mkdirs()) {
            Logger.e("!!! failed to mkdirs");
            return null;
        }
    }
    if (file_name == null) {
        file_path = dir_path + File.separator + generateFileNameBasedOnTimeStamp();
    } else {
        file_path = dir_path + File.separator + file_name;
    }
    Logger.d("... going to return an external dir:" + file_path);
    file = new File(file_path);
    if (file.exists()) {
        Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
        if (!file.delete()) {
            Logger.e("!!! failed to delete file");
            return null;
        }
    }
    return file;
}

public File createInternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File dir ;
    File file;
    if (dir_name == null) {
        dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
    } else {
        dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
    }
    dir_path = dir.getAbsolutePath();
    Logger.d("... going to access an internal dir:" + dir_path);
    if (!dir.exists()) {
        Logger.d("... going to mkdirs:" + dir_path);
        if (!dir.mkdirs()) {
            Logger.e("!!! mkdirs failed");
            return null;
        }
    }
    if (file_name == null) {
        file = new File(dir, generateFileNameBasedOnTimeStamp());
    } else {
        file = new File(dir, file_name);
    }
    file_path = file.getAbsolutePath();
    Logger.d("... going to return an internal dir:" + file_path);
    if (file.exists()) {
        Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
        if (!file.delete()) {
            Logger.e("!!! failed to delete file");
            return null;
        }
    }
    return file;
}

public File getExternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File file;
    if (!isExternalStorageWritable(context)) {
        Logger.e("!!! external storage not writable");
        return null;
    }
    if (dir_name == null) {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
    } else {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
    }
    if (file_name == null) {
        file_path = dir_path;
    } else {
        file_path = dir_path + File.separator + file_name;
    }
    Logger.d("... going to return an external file:" + file_path);
    file = new File(file_path);
    if (file.exists()) {
        Logger.d("... file exists:" + file.getAbsolutePath());
    } else {
        Logger.e("!!! file does't exist:" + file.getAbsolutePath());
    }
    return file;
}

public File getInternalFile(String dir_name, String file_name, Context context) {
    String file_path;
    File dir ;
    File file;
    if (dir_name == null) {
        dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
    } else {
        dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
    }
    if (file_name == null) {
        file = new File(dir.getAbsolutePath());
    } else {
        file = new File(dir, file_name);
    }
    file_path = file.getAbsolutePath();
    Logger.d("... going to return an internal dir:" + file_path);
    if (file.exists()) {
        Logger.d("... file exists:" + file.getAbsolutePath());
    } else {
        Logger.e("!!! file does't exist:" + file.getAbsolutePath());
    }
    return file;
}

private byte[] readBytesFromFile(File file) {
    Logger.d(">>> path:" + file.getAbsolutePath());
    FileInputStream fis;
    long file_length;
    byte[] buffer;
    int offset = 0;
    int next = 0;
    if (!file.exists()) {
        Logger.e("!!! file doesn't exists");
        return null;
    }
    if (file.length() > Integer.MAX_VALUE) {
        Logger.e("!!! file length is out of max of int");
        return null;
    } else {
        file_length = file.length();
    }
    try {
        fis = new FileInputStream(file);
        //buffer = new byte[(int) file_length];
        buffer = new byte[(int) file.length()];
        long time_start = System.currentTimeMillis();
        while (true) {
            Logger.d("... now next:" + next + " and offset:" + offset);
            if (System.currentTimeMillis() - time_start > 1000) {
                Logger.e("!!! left due to time out");
                break;
            }
            next = fis.read(buffer, offset, (buffer.length-offset));
            if (next < 0 || offset >= buffer.length) {
                Logger.d("... completed to read");
                break;
            }
            offset += next;
        }
        //if (offset < buffer.length) {
        if (offset < (int) file_length) {
            Logger.e("!!! not complete to read");
            return null;
        }
        fis.close();
        return buffer;
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

public byte[] readBytesFromFile(File file, boolean is_fis_fos_only) {
    if (file == null) return null;
    if (is_fis_fos_only) {
        return readBytesFromFile(file);
    }
    Logger.d(">>> path:" + file.getAbsolutePath());
    FileInputStream fis;
    BufferedInputStream bis;
    ByteArrayOutputStream bos;
    byte[] buf = new byte[(int) file.length()];
    int num_read;
    if (!file.exists()) {
        Logger.e("!!! file doesn't exists");
        return null;
    }
    try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        bos = new ByteArrayOutputStream();
        long time_start = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis() - time_start > 1000) {
                Logger.e("!!! left due to time out");
                break;
            }
            num_read = bis.read(buf, 0, buf.length); //1024 bytes per call
            if (num_read < 0) break;
            bos.write(buf, 0, num_read);
        }
        buf = bos.toByteArray();
        fis.close();
        bis.close();
        bos.close();
        return buf;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Logger.e("!!! FileNotFoundException");
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

/**
 * streams (InputStream and OutputStream) transfer binary data
 * if to write a string to a stream, must first convert it to bytes, or in other words encode it
 */
public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}

/**
 * io blocks until some input/output is available.
 */
public boolean copy(File source, File destination) {
    if (source == null || destination == null) return false;
    Logger.d(">>> source:" + source.getAbsolutePath() + ", destination:" + destination.getAbsolutePath());
    try {
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destination);
        byte[] buffer = new byte[(int) source.length()];
        int len;
        while (EOF != (len = fis.read(buffer))) {
            fos.write(buffer, 0, len);
        }
        if (true) { //debug
            byte[] copies = readBytesFromFile(destination);
            if (copies != null) {
                int copy_len = copies.length;
                Logger.d("... stream read and write done for " + copy_len + " bytes");
            }
        }
        return destination.length() != 0;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

public void list(final String path, final String end, final List<File> files) {
    Logger.d(">>> path:" + path + ", end:" + end);
    File file = new File(path);
    if (file.isDirectory()) {
        for (File child : file.listFiles()){
            list(child.getAbsolutePath(), end, files);
        }
    } else if (file.isFile()) {
        if (end.equals("")) {
            files.add(file);
        } else {
            if (file.getName().endsWith(end)) files.add(file);
        }
    }
}

public String[] splitFileName(File file, String split) {
    String path;
    String ext;
    int lastIndexOfSplit = file.getAbsolutePath().lastIndexOf(split);
    if (lastIndexOfSplit < 0) {
        path = file.getAbsolutePath();
        ext = "";
    } else {
        path = file.getAbsolutePath().substring(0, lastIndexOfSplit);
        ext = file.getAbsolutePath().substring(lastIndexOfSplit);
    }
    return new String[] {path, ext};
}

public File rename(File old_file, String new_name) {
    if (old_file == null || new_name == null) return null;
    Logger.d(">>> old file path:" + old_file.getAbsolutePath() + ", new file name:" + new_name);
    File new_file = new File(old_file, new_name);
    if (!old_file.equals(new_file)) {
        if (new_file.exists()) { //if find out previous file/dir at new path name exists
            if (new_file.delete()) {
                Logger.d("... succeeded to delete previous file at new abstract path name:" + new_file.getAbsolutePath());
            } else {
                Logger.e("!!! failed to delete previous file at new abstract path name");
                return null;
            }
        }
        if (old_file.renameTo(new_file)) {
            Logger.d("... succeeded to rename old file to new abstract path name:" + new_file.getAbsolutePath());
        } else {
            Logger.e("!!! failed to rename old file to new abstract path name");
        }
    } else {
        Logger.d("... new and old file have the equal abstract path name:" + new_file.getAbsolutePath());
    }
    return new_file;
}

public boolean remove(final String path, final String end) {
    Logger.d(">>> path:" + path + ", end:" + end);
    File file = new File(path);
    boolean result = false;
    if (file.isDirectory()) {
        for (File child : file.listFiles()){
            result = remove(child.getAbsolutePath(), end);
        }
    } else if (file.isFile()) {
        if (end.equals("")) {
            result = file.delete();
        } else {
            if (file.getName().endsWith(end)) result = file.delete();
        }
    } else {
        Logger.e("!!! child is not file or directory");
    }
    return result;
}

@TargetApi(Build.VERSION_CODES.O)
public byte[] readNIOBytesFromFile(String path) throws IOException {
    Logger.d(">>> path:" + path);
    if (!Files.exists(Paths.get(path), LinkOption.NOFOLLOW_LINKS)) {
        Logger.e("!!! file doesn't exists");
        return null;
    } else {
        return Files.readAllBytes(Paths.get(path));
    }
}

@TargetApi(Build.VERSION_CODES.O)
public File writeNIOBytesToFile(String dir, String name, byte[] data) {
    Logger.d(">>> dir:" + dir + ", name:" + name);
    Path path_dir;
    Path path_file;
    try {
        if (!Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS)) {
            Logger.d("... make a dir");
            path_dir = Files.createDirectories(Paths.get(dir));
            if (path_dir == null) {
                Logger.e("!!! failed to make a dir");
                return null;
            }
        }
        path_file = Files.write(Paths.get(name), data);
        return path_file.toFile();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

@TargetApi(Build.VERSION_CODES.O)
public void listNIO(final String dir, final String end, final List<File> files) throws IOException {
    Logger.d(">>> dir:" + dir + ", end:" + end);
    Files.walkFileTree(Paths.get(dir), new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            Logger.d("... file:" + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            Logger.d("... file:" + file.getFileName());
            if (end.equals("")) {
                files.add(file.toFile());
            } else {
                if (file.endsWith(end)) files.add(file.toFile());
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            Logger.d("... file:" + file.getFileName());
            if (end.equals("")) {
                files.add(file.toFile());
            } else {
                if (file.endsWith(end)) files.add(file.toFile());
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
            Logger.d("... file:" + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }
    });
}

/**
 * recursion
 */
private int factorial (int x) {
    if (x > 1) return (x*(factorial(x-1)));
    else if (x == 1) return x;
    else return 0;
}

}

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

Cannot create PoolableConnectionFactory

Here it was caused by avast antivirus. You can disable the avast firewall and let only windows firewall active.

How to render a PDF file in Android

I have made a hybrid approach from some of the answers given to this and other similar posts:

This solution checks if a PDF reader app is installed and does the following: - If a reader is installed, download the PDF file to the device and start a PDF reader app - If no reader is installed, ask the user if he wants to view the PDF file online through Google Drive

NOTE! This solution uses the Android DownloadManager class, which was introduced in API9 (Android 2.3 or Gingerbread). This means that it doesn't work on Android 2.2 or earlier.

I wrote a blog post about it here, but I've provided the full code below for completeness:

public class PDFTools {
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader. 
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
     * <br />
     * <b>BEWARE:</b> This method
     * @param context
     * @param pdfUrl
     * @return
     */
    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl); 
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}

SSIS Connection not found in package

In my case, I could solve this in an easier way. I opened the x.dtsConfig archive, and for an unknown reason this archive was not in the standard format, so ssis could not recognize the configurations. Fortunately, I had backed up the archive previously, so I just had to copy it to the original folder, and everything was working again.

Is there a JSON equivalent of XQuery/XPath?

Just to add to the choices, there's also XPath. XPath 3.1 handles JSON as well as XML. In XPath 3.1 your required query is ?0?Objects?*[?id=3]

How do I push to GitHub under a different username?

It's simple while cloning please take the git URL with your username.While committing it will ask your new user password.

Eg:

git clone https://[email protected]/username/reponame.git

git clone https://[email protected]/username/reponame.git

How to initialize an array in one step using Ruby?

Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

PowerShell: Store Entire Text File Contents in Variable

One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:

$content = ${C:file.txt}

This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:

 ${D:\path\to\file.txt} = $content

Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:

${C:file.txt} = ${C:file.txt} | select -skip 1

I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.

One final note on using this: you must use a drive designation, i.e. ${drive:filespec} as I have done in all the examples above. Without the drive (e.g. ${file.txt}) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

How to change the datetime format in pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

csv.Error: iterator should return strings, not bytes

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

How can I convert a DateTime to the number of seconds since 1970?

If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:

long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

Storing and retrieving datatable from session

Add a datatable into session:

DataTable Tissues = new DataTable();

Tissues = dal.returnTissues("TestID", "TestValue");// returnTissues("","") sample     function for adding values


Session.Add("Tissues", Tissues);

Retrive that datatable from session:

DataTable Tissues = Session["Tissues"] as DataTable

or

DataTable Tissues = (DataTable)Session["Tissues"];

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

How do you discover model attributes in Rails?

If you're just interested in the properties and data types from the database, you can use Model.inspect.

irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
 reset_password_token: string, reset_password_sent_at: datetime,
 remember_created_at: datetime, sign_in_count: integer,
 current_sign_in_at: datetime, last_sign_in_at: datetime,
 current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
 updated_at: datetime)"

Alternatively, having run rake db:create and rake db:migrate for your development environment, the file db/schema.rb will contain the authoritative source for your database structure:

ActiveRecord::Schema.define(version: 20130712162401) do
  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

Convert the first element of an array to a string in PHP

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

How can I output the value of an enum class in C++11

You could do something like this:

//outside of main
namespace A
{
    enum A
    {
        a = 0,
        b = 69,
        c = 666
    };
};

//in main:

A::A a = A::c;
std::cout << a << std::endl;

Amazon S3 - HTTPS/SSL - Is it possible?

As previously stated, it's not directly possible, but you can set up Apache or nginx + SSL on a EC2 instance, CNAME your desired domain to that, and reverse-proxy to the (non-custom domain) S3 URLs.

How to display all elements in an arraylist?

Your getAll() method does not get all. It returns the first car.

The return statement terminates the loop.

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

HTML Table cellspacing or padding just top / bottom

CSS?

td {
  padding-top: 2px;
  padding-bottom: 2px;
}

Select a date from date picker using Selenium webdriver

This code should work properly to get the current date from the calendar.

String today=getCurrentDay(); //function 
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));

    for (WebElement cell: columns) {
      String z=cell.getAttribute("class").toString();
      if(z.equalsIgnoreCase("day")){
      if (cell.getText().equals(today)) {
        cell.click();
        break;
      }
    }

private String getCurrentDay() {
 Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
 //Get Current Day as a number
 int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
 System.out.println("Today Int: " + todayInt +"\n");

 //Integer to String Conversion
 String todayStr = Integer.toString(todayInt);
 return todayStr;
}

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

When is the init() function run?

init will be called everywhere uses its package(no matter blank import or import), but only one time.

this is a package:

package demo

import (
    "some/logs"
)

var count int

func init() {
    logs.Debug(count)
}

// Do do
func Do() {
    logs.Debug("dd")
}

any package(main package or any test package) import it as blank :

_ "printfcoder.com/we/models/demo"

or import it using it func:

"printfcoder.com/we/models/demo"

func someFunc(){
   demo.Do()
}

the init will log 0 only one time. the first package using it, its init func will run before the package's init. So:

A calls B, B calls C, all of them have init func, the C's init will be run first before B's, B's before A's.

Explanation of JSONB introduced by PostgreSQL

Regarding the differences between json and jsonb datatypes, it worth mentioning the official explanation:

PostgreSQL offers two types for storing JSON data: json and jsonb. To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14.6.

The json and jsonb data types accept almost identical sets of values as input. The major practical difference is one of efficiency. The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed. jsonb also supports indexing, which can be a significant advantage.

Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept.

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

PostgreSQL allows only one character set encoding per database. It is therefore not possible for the JSON types to conform rigidly to the JSON specification unless the database encoding is UTF8. Attempts to directly include characters that cannot be represented in the database encoding will fail; conversely, characters that can be represented in the database encoding but not in UTF8 will be allowed.

Source: https://www.postgresql.org/docs/current/datatype-json.html

iPhone App Icons - Exact Radius?

I tried 228px radius for 1024x1024 and it worked :)

SQL- Ignore case while searching for a string

Use something like this -

SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')

or

SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

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

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

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

Tx prop REQUIRES_NEW

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

How can I get the current class of a div with jQuery?

var className=$('selector').attr('class');

or

var className=$(this).attr('class');

the classname of the current element

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

What's the best way to add a full screen background image in React Native

(This has been deprecated now you can use ImageBackground)

This is how I've done it. The main deal was getting rid of the static fixed sizes.

class ReactStrap extends React.Component {
  render() {
    return (
      <Image source={require('image!background')} style={styles.container}>
        ... Your Content ...
      </Image>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    // remove width and height to override fixed static size
    width: null,
    height: null,
  }
};

how to import csv data into django models

define class in models.py and a function in it.

class all_products(models.Model):
    def get_all_products():
        items = []
        with open('EXACT FILE PATH OF YOUR CSV FILE','r') as fp:
            # You can also put the relative path of csv file
            # with respect to the manage.py file
            reader1 = csv.reader(fp, delimiter=';')
            for value in reader1:
                items.append(value)
        return items

You can access ith element in the list as items[i]

Using msbuild to execute a File System Publish Profile

Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild

Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).

Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.

Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.

Publish to File System

The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.

This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:

<Target Name="PublishToFileSystem"
        DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
    <Error Condition="'$(PublishDestination)'==''"
           Text="The PublishDestination property must be set to the intended publishing destination." />
    <MakeDir Condition="!Exists($(PublishDestination))"
             Directories="$(PublishDestination)" />

    <ItemGroup>
        <PublishFiles Include="$(_PackageTempDir)\**\*.*" />
    </ItemGroup>

    <Copy SourceFiles="@(PublishFiles)"
          DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
          SkipUnchangedFiles="True" />
</Target>

This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.

The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.

We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).

To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):

msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem

How can I disable a button in a jQuery dialog from a function?

I got this working with the method .dialog("widget") which returns the dialog DIV itself. If you're in the dialog methods:

$(this)
.dialog("widget")
.find("button")
.addClass("ui-state-disabled") // for the style
.attr("disabled", true);

How to add footnotes to GitHub-flavoured Markdown?

I used a variant of Mateo's solution. I'm using this in Rmd files written in github flavored markdown (gfm) for a Jekyll powered website but the same Rmd files are being used to produce pdfs in various contexts. The Rmd files are math heavy and the math is displayed with MathJax on the website. So I needed a solution that works with gfm that is processed via Jekyll, works with pandoc->pdflatex, and is compatible with MathJax.

snippet from Rmd file (which is gfm)

Here is a paragraph with an footnote <span id="a1">[[1]](#f1)</span>.

Footnotes
=========

1. <span id="f1"></span> This is a footnote. [$\hookleftarrow$](#a1)

$\hookleftarrow$ is latex, which works for me since I always have MathJax enabled. I use that to make sure it shows up correctly in my pdfs. I put my footnotes in square brackets because superscript is confusing if I am putting a footnote on some inline math.

Here it is in action: https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/

These notes can be put anywhere in the Rmd. I am putting in a list at the end so they are technically endnotes.

Check if a column contains text using SQL

Try LIKE construction, e.g. (assuming StudentId is of type Char, VarChar etc.)

  select * 
    from Students
   where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain

"detached entity passed to persist error" with JPA/EJB code

remove

user.setId(1);

because it is auto generate on the DB, and continue with persist command.

jQuery UI 1.10: dialog and zIndex option

You may want to try jQuery dialog method:

$( ".selector" ).dialog( "moveToTop" );

reference: http://api.jqueryui.com/dialog/#method-moveToTop

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

proper way to sudo over ssh

The best way is ssh -t user@server "sudo <scriptname>", for example ssh -t user@server "sudo reboot". It will prompt for password for user first and then root(since we are running the script or command with root privilege.

I hope it helped and cleared your doubt.

How to change UIPickerView height

As mentioned above UIPickerView is now resizable. I just want to add though that if you want to change the pickerView's height in a tableView Cell, I didn't have any success with setting the height anchor to a constant. However, using lessThanOrEqualToConstant seems to work.

 class PickerViewCell: UITableViewCell {

    let pickerView = UIPickerView()

    func setup() {

        // call this from however you initialize your cell

        self.contentView.addSubview(self.pickerView)
        self.pickerView.translatesAutoresizingMaskIntoConstraints = false

        let constraints: [NSLayoutConstraint] = [
            // pin the pickerView to the contentView's layoutMarginsGuide

            self.pickerView.leadingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.leadingAnchor),
            self.pickerView.topAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.topAnchor),
            self.pickerView.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
            self.pickerView.bottomAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.bottomAnchor),

            // set the height using lessThanOrEqualToConstant
            self.pickerView.heightAnchor.constraint(lessThanOrEqualToConstant: 100)
        ]

        NSLayoutConstraint.activate(constraints)
     }

 }

Adding local .aar files to Gradle build using "flatDirs" is not working

Edit: The correct way (currently) to use a local AAR file as a build dependency is to use the module import wizard (File | New Module | Import .JAR or .AAR package) which will automatically add the .aar as a library module in your project.

Old Answer

Try this:

allprojects {
  repositories {
    jcenter()
    flatDir {
      dirs 'libs'
    }
  }
}

...

compile(name:'slidingmenu', ext:'aar')

Automatically create requirements.txt

if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.

How to track down access violation "at address 00000000"

I will second madExcept and similar tools, like Eurekalog, but I think you can come a good way with FastMM also. With full debugmode enabled, it should give you some clues of whats wrong.

Anyway, even though Delphi uses FastMM as default, it's worth getting the full FastMM for it's additional control over logging.

How to create border in UIButton?

Swift 5

button.layer.borderWidth = 2

To change the colour of the border use

button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)

How to automatically update your docker containers, if base-images are updated

have you tried this: https://github.com/v2tec/watchtower. it's a simple tool running in docker container watching other containers, if their base image changed, it will pull and redeploy.

Android Overriding onBackPressed()

Override the onBackPressed() method as per the example by codeMagic, and remove the call to super.onBackPressed(); if you do not want the default action (finishing the current activity) to be executed.

CSS hexadecimal RGBA?

RGB='#ffabcd';
A='0.5';
RGBA='('+parseInt(RGB.substring(1,3),16)+','+parseInt(RGB.substring(3,5),16)+','+parseInt(RGB.substring(5,7),16)+','+A+')';

Print array without brackets and commas

I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ",""); as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.

How to Use -confirm in PowerShell

Write-Warning "This is only a test warning." -WarningAction Inquire

from: https://serverfault.com/a/1015583/584478

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

versionCode vs versionName in Android Manifest

Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.

Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.

For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).

Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".

Hope that helps.

You can read more about it here

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

set define off;

Alternatively, hacky:

update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

jQuery UI Dialog - missing close icon

I am late to this one by a while, but I'm going to blow your mind, ready?

The reason this is happening, is because you are calling bootstrap in, after you are calling jquery-ui in.

Literally, swap the two so that instead of:

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>

it becomes

<script src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

:)

Edit - 26/06/2015 - this keeps attracting interest months later so I thought it was worth an edit. I actually really like the noConflict solution offered in the comment underneath this answer and clarified by user Pretty Cool as a separate answer. As some have reported issues with the bootstrap tooltip when the scripts are swapped. I didn't experience that issue however because I downloaded jquery UI without the tooltip as I didn't need it because bootstrap. So this issue never came up for me.

Edit - 22/07/2015 - Don't confuse jquery-ui with jquery! While Bootstrap's JavaScript requires jQuery to be loaded before, it doesn't rely on jQuery-UI. So jquery-ui.js can be loaded after bootstrap.min.js, while jquery.js always needs to be loaded before Bootstrap.

MySQL: Set user variable from result of query

Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

What's the "Content-Length" field in HTTP header?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 1024

Applications SHOULD use this field to indicate the transfer-length of the message-body.

In PHP you would use something like this.

header("Content-Length: ".filesize($filename));

In case of "Content-Type: application/x-www-form-urlencoded" the encoded data is sent to the processing agent designated so you can set the length or size of the data you are going to post.

How can I print literal curly-brace characters in a string and also use .format on it?

I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

You can then do something like:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

Gets the job done if performance is not an issue.

Standard concise way to copy a file in Java?

  • These methods are performance-engineered (they integrate with operating system native I/O).
  • These methods work with files, directories and links.
  • Each of the options supplied may be left out - they are optional.

The utility class

package com.yourcompany.nio;

class Files {

    static int copyRecursive(Path source, Path target, boolean prompt, CopyOptions options...) {
        CopyVisitor copyVisitor = new CopyVisitor(source, target, options).copy();
        EnumSet<FileVisitOption> fileVisitOpts;
        if (Arrays.toList(options).contains(java.nio.file.LinkOption.NOFOLLOW_LINKS) {
            fileVisitOpts = EnumSet.noneOf(FileVisitOption.class) 
        } else {
            fileVisitOpts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        }
        Files.walkFileTree(source[i], fileVisitOpts, Integer.MAX_VALUE, copyVisitor);
    }

    private class CopyVisitor implements FileVisitor<Path>  {
        final Path source;
        final Path target;
        final CopyOptions[] options;

        CopyVisitor(Path source, Path target, CopyOptions options...) {
             this.source = source;  this.target = target;  this.options = options;
        };

        @Override
        FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        // before visiting entries in a directory we copy the directory
        // (okay if directory already exists).
        Path newdir = target.resolve(source.relativize(dir));
        try {
            Files.copy(dir, newdir, options);
        } catch (FileAlreadyExistsException x) {
            // ignore
        } catch (IOException x) {
            System.err.format("Unable to create: %s: %s%n", newdir, x);
            return SKIP_SUBTREE;
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        Path newfile= target.resolve(source.relativize(file));
        try {
            Files.copy(file, newfile, options);
        } catch (IOException x) {
            System.err.format("Unable to copy: %s: %s%n", source, x);
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        // fix up modification time of directory when done
        if (exc == null && Arrays.toList(options).contains(COPY_ATTRIBUTES)) {
            Path newdir = target.resolve(source.relativize(dir));
            try {
                FileTime time = Files.getLastModifiedTime(dir);
                Files.setLastModifiedTime(newdir, time);
            } catch (IOException x) {
                System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
            }
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            System.err.println("cycle detected: " + file);
        } else {
            System.err.format("Unable to copy: %s: %s%n", file, exc);
        }
        return CONTINUE;
    }
}

Copying a directory or file

long bytes = java.nio.file.Files.copy( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES,
                 java.nio.file.LinkOption.NOFOLLOW_LINKS);

Moving a directory or file

long bytes = java.nio.file.Files.move( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.ATOMIC_MOVE,
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING);

Copying a directory or file recursively

long bytes = com.yourcompany.nio.Files.copyRecursive( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
                 java.nio.file.LinkOption.NOFOLLOW_LINKS );

Detect if the app was launched/opened from a push notification

For Swift Users:

If you want to launch a different page on opening from push or something like that, you need to check it in didFinishLaunchingWithOptions like:

let directVc: directVC! = directVC(nibName:"directVC", bundle: nil)
let pushVc: pushVC! = pushVC(nibName:"pushVC", bundle: nil)

if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
     self.navigationController = UINavigationController(rootViewController: pushVc!)
} else {
     self.navigationController = UINavigationController(rootViewController: directVc!)
}
self.window!.rootViewController = self.navigationController

How to make Sonar ignore some classes for codeCoverage metric?

I had to struggle for a little bit but I found a solution, I added

-Dsonar.coverage.exclusions=**/*.* 

and the coverage metric was cancelled from the dashboard at all, so I realized that the problem was the path I was passing, not the property. In my case the path to exclude was java/org/acme/exceptions, so I used :

`-Dsonar.coverage.exclusions=**/exceptions/**/*.*` 

and it worked, but since I don't have sub-folders it also works with

-Dsonar.coverage.exclusions=**/exceptions/*.*

How to specify jdk path in eclipse.ini on windows 8 when path contains space

I have Windows 8.1 and my JDK under "Program Files" as well. What worked for me was replacing the name of the folder by the 8-digit internal MS-DOS name.

-vm
C:/PROGRA~1/Java/jdk1.8.0_40/bin/javaw.exe

I realized what was going on after running this in cmd.exe

CD \
DIR P* /X

It returned...

<DIR>          PROGRA~1     Program Files
<DIR>          PROGRA~2     Program Files (x86)

So we can find out how to use a path containing spaces

Setting the default page for ASP.NET (Visual Studio) server configuration

The built-in webserver is hardwired to use Default.aspx as the default page.

The project must have atleast an empty Default.aspx file to overcome the Directory Listing problem for Global.asax.

:)

Once you add that empty file all requests can be handled in one location.

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
        this.Response.StatusCode = 200;
        this.Response.ContentType = "text/plain";

        this.Response.End();
    }
}

Display Image On Text Link Hover CSS Only

It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.

CSS :

.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }

HTML :

<div class="hover_img">
     <a href="#">Show Image<span><img src="images/01.png" alt="image" height="100" /></span></a>
</div>

Alter user defined type in SQL Server

The solutions provided here can only be applied if the user defined types are used in table definitions only, and if the UDT columns are not indexed.

Some developers also have SP's and functions using UDT parameters, which is not covered either. (see comments on Robin's link and in the Connect entry)

The Connect entry from 2007 has finally been closed after 3 years:

Thank you for submitting this suggestion, but given its priority relative to the many other items in our queue, it is unlikely that we will actually complete it. As such, we are closing this suggestion as “won’t fix”.

I tried to solve a similiar problem ALTERing XML SCHEMA COLLECTIONS, and the steps seem to mostly apply to ALTER TYPE, too:

To drop a UDT, the following steps are necessary:

  • If a table column references the UDT, it has to be converted to the underlying type
  • If the table column has a default constraint, drop the default constraint
  • If a procedure or function has UDT parameters, the procedure or function has to be dropped
  • If there is an index on a UDT column, the index has to be dropped
  • If the index is a primary key, all foreign keys have to be dropped
  • If there are computed columns based on a UDT column, the computed columns have to be dropped
  • If there are indexes on these computed columns, the indexes have to be dropped
  • If there are schema-bound views, functions, or procedures based on tables containing UDT columns, these objects have to be dropped

Is there a way to 'uniq' by column?

To consider multiple column.

Sort and give unique list based on column 1 and column 3:

sort -u -t : -k 1,1 -k 3,3 test.txt
  • -t : colon is separator
  • -k 1,1 -k 3,3 based on column 1 and column 3

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Java: parse int value from a char

String a = "jklmn489pjro635ops";

int sum = 0;

String num = "";

boolean notFirst = false;

for (char c : a.toCharArray()) {

    if (Character.isDigit(c)) {
        sum = sum + Character.getNumericValue(c);
        System.out.print((notFirst? " + " : "") + c);
        notFirst = true;
    }
}

System.out.println(" = " + sum);

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

For .NET server can configure this in web.config as shown below

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>

For instance lets say, if the server domain is http://live.makemypublication.com and client is http://www.makemypublication.com then configure in server's web.config as below

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="http://www.makemypublication.com" />
     </customHeaders>
  </httpProtocol>
 </system.webServer>

Open files in 'rt' and 'wt' modes

The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.

Other than U, those mode flags come directly from the standard C library's fopen() function, a fact that is documented in the sixth paragraph of the python2 documentation for open().

As far as I know, t is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.

C++ int to byte array

std::vector<unsigned char> intToBytes(int value)
{
    std::vector<unsigned char> result;
    result.push_back(value >> 24);
    result.push_back(value >> 16);
    result.push_back(value >>  8);
    result.push_back(value      );
    return result;
}

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How to center a Window in Java?

Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.

Sometimes important, sometimes not...

See GraphicsEnvironment javadocs for more info on how to get this.

Difference between java HH:mm and hh:mm on SimpleDateFormat

kk: (01-24) will look like 01, 02..24.

HH:(00-23) will look like 00, 01..23.

hh:(01-12 in AM/PM) will look like 01, 02..12.

so the last printout (working2) is a bit weird. It should say 12:00:00 (edit: if you were setting the working2 timezone and format, which (as kdagli pointed out) you are not)

Avoid Adding duplicate elements to a List C#

Your this check:

if (!lines2.Contains(lines3.ToString()))

is invalid. You are checking if your lines2 contains System.String[] since lines3.ToString() will give you that. You need to check if item from lines3 exists in lines2 or not.

You can iterate each item in lines3 check if it exists in the lines2 and then add it. Something like.

foreach (string str in lines3)
{
    if (!lines2.Contains(str))
        lines2.Add(str);
}

Or if your lines2 is any empty list, then you can simply add the lines3 distinct values to the list like:

lines2.AddRange(lines3.Distinct());

then your lines2 will contain distinct values.

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

No server in windows>preferences

If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon. enter image description here

Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:

enter image description here

What is the difference between JAX-RS and JAX-WS?

i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS

Get the index of the object inside an array, matching a condition

I have seen many solutions in the above.

Here I am using map function to find the index of the search text in an array object.

I am going to explain my answer with using students data.

  • step 1: create array object for the students(optional you can create your own array object).
    var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

  • step 2: Create variable to search text
    var studentNameToSearch = "Divya";

  • step 3: Create variable to store matched index(here we use map function to iterate).
    var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);

_x000D_
_x000D_
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];_x000D_
_x000D_
var studentNameToSearch = "Divya";_x000D_
_x000D_
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);_x000D_
_x000D_
console.log(matchedIndex);_x000D_
_x000D_
alert("Your search name index in array is:"+matchedIndex)
_x000D_
_x000D_
_x000D_

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

Simply create a new column, set the Name to whatever you like, set the Type to INT and check the box that says A_I.

diagram The A_I checkbox stands for AUTO_INCREMENT, which essentially means that sequence numbers are assigned automatically in that new column (see below).

 column1 | column2 | id
-----------------------
 value   | value   | 1
-----------------------
 value   | value   | 2
-----------------------
 value   | value   | 3
-----------------------
 value   | value   | 4

This column essentially acts as a reference for phpMyAdmin to delete rows from. If necessary, click on the unique button for this new column, although this happened automatically for me. After following the above steps, you should no longer have the error message and buttons should appear for editing rows in phpMyAdmin!

How to check String in response body with mockMvc

You can use getContentAsString method to get the response data as string.

    String payload = "....";
    String apiToTest = "....";
    
    MvcResult mvcResult = mockMvc.
                perform(post(apiToTest).
                content(payload).
                contentType(MediaType.APPLICATION_JSON)).
                andReturn();
    
    String responseData = mvcResult.getResponse().getContentAsString();

You can refer this link for test application.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Android Marshmallow many methods are deprecated.

For example, to get color use

ContextCompat.getColor(context, R.color.color_name);

Also to get drawable use

ContextCompat.getDrawable(context, R.drawable.drawble_name);

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

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

You can use method named compareTo, x.compareTo(y). It will return 0 if x and y are equal, 1 if x is greater than y and -1 if x is smaller than y

How to get the background color code of an element in hex?

Adding on @Newred solution. If your style has more than just the background-color you can use this:

$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]

flutter remove back button on appbar

I believe the solutions are the following

You actually either:

  • Don't want to display that ugly back button ( :] ), and thus go for : AppBar(...,automaticallyImplyLeading: false,...);

  • Don't want the user to go back - replacing current view - and thus go for: Navigator.pushReplacementNamed(## your routename here ##);

  • Don't want the user to go back - replacing a certain view back in the stack - and thus use: Navigator.pushNamedAndRemoveUntil(## your routename here ##, f(Route<dynamic>)?bool); where f is a function returning truewhen meeting the last view you want to keep in the stack (right before the new one);

  • Don't want the user to go back - EVER - emptying completely the navigator stack with: Navigator.pushNamedAndRemoveUntil(context, ## your routename here ##, (_) => false);

Cheers

Calculating text width

I modified Nico's code to work for my needs.

$.fn.textWidth = function(){
    var self = $(this),
        children = self.contents(),
        calculator = $('<span style="white-space:nowrap;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

I'm using .contents() as .children() does not return text nodes which I needed. I also found that the returned width was impacted by the viewport width which was causing wrapping so I'm using white-space:nowrap; to get the correct width regardless of viewport width.

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

HttpGet with HTTPS : SSLPeerUnverifiedException

Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

How to post object and List using postman

Make sure that you have made the content-type as application/json in header request and Post from body under the raw tab.

{
  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay",
  "arrayObjectName" : [{
    "Id" : 1,
    "Name": "ABC" },
    {
    "Id" : 2,
    "Name" : "XYZ"
  }],
  "intArrayName" : [111,222,333],
  "stringArrayName" : ["a","b","c"]


}

YouTube Video Embedded via iframe Ignoring z-index?

BigJacko's Javascript code worked for me, but in my case I first had to add some JQuery "noconflict" code. Here's the revised version that worked on my site:

<script type="text/javascript">
var $j = jQuery.noConflict(); 
jQuery(document).ready(function($j){
  $j('iframe').each(function() {
    var url = $j(this).attr("src");
      if ($j(this).attr("src").indexOf("?") > 0) {
        $j(this).attr({
          "src" : url + "&wmode=transparent",
          "wmode" : "Opaque"
        });
      }
      else {
        $j(this).attr({
          "src" : url + "?wmode=transparent",
           "wmode" : "Opaque"
        });
      }
   });
});
</script>

How to copy folders to docker image from Dockerfile?

Use ADD (docs)

The ADD command can accept as a <src> parameter:

  1. A folder within the build folder (the same folder as your Dockerfile). You would then add a line in your Dockerfile like this:
ADD folder /path/inside/your/container

or

  1. A single-file archive anywhere in your host filesystem. To create an archive use the command:
tar -cvzf newArchive.tar.gz /path/to/your/folder

You would then add a line to your Dockerfile like this:

ADD /path/to/archive/newArchive.tar.gz  /path/inside/your/container

Notes:

  • ADD will automatically extract your archive.
  • presence/absence of trailing slashes is important, see the linked docs

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

Calling a Fragment method from a parent Activity

I don't know about Java, but in C# (Xamarin.Android) there is no need to look up the fragment everytime you need to call the method, see below:

public class BrandActivity : Activity
{
    MyFragment myFragment;

    protected override void OnCreate(Bundle bundle)
    {       
        // ...
        myFragment = new MyFragment();      
        // ...
    }

    void someMethod()
    {
        myFragment.MyPublicMethod();
    }
}

public class MyFragment : Android.Support.V4.App.Fragment
{
    public override void OnCreate(Bundle bundle)
    {
        // ...
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
    {
        // ...
    }

    public void MyPublicMethod()
    {
        // ...
    }   
}

I think in Java you can do the same.