SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

how to iterate through dictionary in a dictionary in django template?

Lets say your data is -

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

Iterating through a golang map

You can make it by one line:

mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
    fmt.Println("k:", k, "v:", v)
}

Output is:

k: foo v: map[first:1]
k: boo v: map[second:2]

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How to stop a vb script running in windows

Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.

How to pass a URI to an intent?

If you want to use standard extra data field, you would do something like this:

private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra(Intent.EXTRA_STREAM, imageUri.toString());
startActivity(intent);
this.finish();

The documentation for Intent says:

EXTRA_STREAM   added in API level 1 
String EXTRA_STREAM
A content: URI holding a stream of data associated with the Intent,
used with ACTION_SEND to supply the data being sent. 

Constant Value: "android.intent.extra.STREAM"

You don't have to use the built-in standard names, but it's probably good practice and more reusable. Take a look at the developer documentation for a list of all the built-in standard extra data fields.

Definition of a Balanced Tree

Balanced tree is a tree whose height is of order of log(number of elements in the tree).

height = O(log(n))
O, as in asymptotic notation i.e. height should have same or lower asymptotic
growth rate than log(n)
n: number of elements in the tree

The definition given "a tree is balanced of each sub-tree is balanced and the height of the two sub-trees differ by at most one" is followed by AVL trees.

Since, AVL trees are balanced but not all balanced trees are AVL trees, balanced trees don't hold this definition and internal nodes can be unbalanced in them. However, AVL trees require all internal nodes to be balanced.

PHP CURL Enable Linux

It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

You can flush hosts local MySQL using following command:

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

In additional suggestion you can permanently solve blocked of many connections error problem by editing my.ini file[Mysql configuration file]

change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

C# Call a method in a new thread

Once a thread is started, it is not necessary to retain a reference to the Thread object. The thread continues to execute until the thread procedure ends.

new Thread(new ThreadStart(SecondFoo)).Start();

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

_x000D_
_x000D_
 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
        _x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    window.onload = function (e) {_x000D_
_x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_
        });_x000D_
    };_x000D_
</script>
_x000D_
_x000D_
_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

Create a unique number with javascript time

Posting this code snippet here for my own future reference (not guaranteed but satisfactory "unique" enough):

// a valid floating number
window.generateUniqueNumber = function() {
    return new Date().valueOf() + Math.random();
};

// a valid HTML id
window.generateUniqueId = function() {
    return "_" + new Date().valueOf() + Math.random().toFixed(16).substring(2);
};

open read and close a file in 1 line of code

with open('pagehead.section.htm')as f:contents=f.read()

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

If you want n bits specific then you could first create a bitmask and then AND it with your number to take the desired bits.

Simple function to create mask from bit a to bit b.

unsigned createMask(unsigned a, unsigned b)
{
   unsigned r = 0;
   for (unsigned i=a; i<=b; i++)
       r |= 1 << i;

   return r;
}

You should check that a<=b.

If you want bits 12 to 16 call the function and then simply & (logical AND) r with your number N

r = createMask(12,16);
unsigned result = r & N;

If you want you can shift the result. Hope this helps

How to count check-boxes using jQuery?

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

Function to close the window in Tkinter

def quit(self):
    self.root.destroy()

Add parentheses after destroy to call the method.

When you use command=self.root.destroy you pass the method to Tkinter.Button without the parentheses because you want Tkinter.Button to store the method for future calling, not to call it immediately when the button is created.

But when you define the quit method, you need to call self.root.destroy() in the body of the method because by then the method has been called.

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

How to convert DataTable to class Object?

Amit, I have used one way to achieve this with less coding and more efficient way.

but it uses Linq.

I posted it here because maybe the answer helps other SO.

Below DAL code converts datatable object to List of YourViewModel and it's easy to understand.

public static class DAL
{
        public static string connectionString = ConfigurationManager.ConnectionStrings["YourWebConfigConnection"].ConnectionString;

        // function that creates a list of an object from the given data table
        public static List<T> CreateListFromTable<T>(DataTable tbl) where T : new()
        {
            // define return list
            List<T> lst = new List<T>();

            // go through each row
            foreach (DataRow r in tbl.Rows)
            {
                // add to the list
                lst.Add(CreateItemFromRow<T>(r));
            }

            // return the list
            return lst;
        }

        // function that creates an object from the given data row
        public static T CreateItemFromRow<T>(DataRow row) where T : new()
        {
            // create a new object
            T item = new T();

            // set the item
            SetItemFromRow(item, row);

            // return 
            return item;
        }

        public static void SetItemFromRow<T>(T item, DataRow row) where T : new()
        {
            // go through each column
            foreach (DataColumn c in row.Table.Columns)
            {
                // find the property for the column
                PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

                // if exists, set the value
                if (p != null && row[c] != DBNull.Value)
                {
                    p.SetValue(item, row[c], null);
                }
            }
        }

        //call stored procedure to get data.
        public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection con = new SqlConnection(connectionString);

            try
            {
                cmd = new SqlCommand(SPName, con);
                cmd.Parameters.AddRange(SqlPrms);
                cmd.CommandTimeout = 240;
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(ds);
            }
            catch (Exception ex)
            {
               return ex;
            }

            return ds;
        }
}

Now, The way to pass and call method is below.

    DataSet ds = DAL.GetRecordWithExtendedTimeOut("ProcedureName");

    List<YourViewModel> model = new List<YourViewModel>();

    if (ds != null)
    {
        //Pass datatable from dataset to our DAL Method.
        model = DAL.CreateListFromTable<YourViewModel>(ds.Tables[0]);                
    }      

Till the date, for many of my applications, I found this as the best structure to get data.

drag drop files into standard html file input

This is the "DTHML" HTML5 way to do it. Normal form input (which IS read only as Ricardo Tomasi pointed out). Then if a file is dragged in, it is attached to the form. This WILL require modification to the action page to accept the file uploaded this way.

_x000D_
_x000D_
function readfiles(files) {_x000D_
  for (var i = 0; i < files.length; i++) {_x000D_
    document.getElementById('fileDragName').value = files[i].name_x000D_
    document.getElementById('fileDragSize').value = files[i].size_x000D_
    document.getElementById('fileDragType').value = files[i].type_x000D_
    reader = new FileReader();_x000D_
    reader.onload = function(event) {_x000D_
      document.getElementById('fileDragData').value = event.target.result;}_x000D_
    reader.readAsDataURL(files[i]);_x000D_
  }_x000D_
}_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondragend = function () { this.className = ''; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
  this.className = '';_x000D_
  e.preventDefault();_x000D_
  readfiles(e.dataTransfer.files);_x000D_
}
_x000D_
#holder.hover { border: 10px dashed #0c0 !important; }
_x000D_
<form method="post" action="http://example.com/">_x000D_
  <input type="file"><input id="fileDragName"><input id="fileDragSize"><input id="fileDragType"><input id="fileDragData">_x000D_
  <div id="holder" style="width:200px; height:200px; border: 10px dashed #ccc"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

It is even more boss if you can make the whole window a drop zone, see How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

Get current date, given a timezone in PHP?

<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>

Force add despite the .gitignore file

See man git-add:

   -f, --force
       Allow adding otherwise ignored files.

So run this

git add --force my/ignore/file.foo

SQL Server: combining multiple rows into one row

Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -

SELECT group_concat(STRINGVALUE) 
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602

Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.

To set the value of group_concat_max_len, execute the below command-

SET group_concat_max_len = 50000;

You can change the value 50000 accordingly, you increase it to a higher value as required.

How to create an instance of System.IO.Stream stream

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How do I properly compare strings in C?

How do I properly compare strings?

char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow

// insufficient
while (check != input)

// good
while (strcmp(check, input) != 0)
// or 
while (strcmp(check, input))

Let us dig deeper to see why check != input is not sufficient.

In C, string is a standard library specification.

A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1

input above is not a string. input is array 40 of char.

The contents of input can become a string.

In most cases, when an array is used in an expression, it is converted to the address of its 1st element.

The below converts check and input to their respective addresses of the first element, then those addresses are compared.

check != input   // Compare addresses, not the contents of what addresses reference

To compare strings, we need to use those addresses and then look at the data they point to.
strcmp() does the job. §7.23.4.2

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Not only can code find if the strings are of the same data, but which one is greater/less when they differ.

The below is true when the string differ.

strcmp(check, input) != 0

For insight, see Creating my own strcmp() function

Dynamically create and submit form

Its My version without jQuery, simple function can be used on fly

Function:

function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Usage:

post_to_url('fullurlpath', {
    field1:'value1',
    field2:'value2'
}, 'post');

How to easily initialize a list of Tuples?

One technique I think is a little easier and that hasn't been mentioned before here:

var asdf = new [] { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
}.ToList();

I think that's a little cleaner than:

var asdf = new List<Tuple<int, string>> { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
};

How do you check whether a number is divisible by another number (Python)?

Try this ...

public class Solution {

  public static void main(String[] args) {
    long t = 1000;
    long sum = 0;

    for(int i = 1; i<t; i++){
            if(i%3 == 0 || i%5 == 0){
                sum = sum + i;
            }
        }
        System.out.println(sum);    
  }
}

What are all the uses of an underscore in Scala?

From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):

import scala._    // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]]       // Higher kinded type parameter
def f(m: M[_])    // Existential type
_ + _             // Anonymous function placeholder parameter
m _               // Eta expansion of method into method value
m(_)              // Partial function application
_ => 5            // Discarded parameter
case _ =>         // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10)  // same thing
f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _    // Initialization to the default value
def abc_<>!       // An underscore must separate alphanumerics from symbols on identifiers
t._2              // Part of a method name, such as tuple getters
1_000_000         // Numeric literal separator (Scala 2.13+)

This is also part of this question.

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Python datetime to string without microsecond component

I usually do:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

output:

2019-01-13 14:40:28

How to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

REST API Authentication

I've been using the JWT authentication. Works just fine in my application.

There is an authentication method that will require the user credentials. This method validates the credentials and returns an access token in case of success.

This token must be sent to every other method in my Web API in the header of the request.

It's pretty easy to implement, and very easy to test.

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

Escaping quotation marks in PHP

Use the addslashes function:

 $str = "Is your name O'Reilly?";

 // Outputs: Is your name O\'Reilly?
   echo addslashes($str);

Redeploy alternatives to JRebel

JRebel is free. Don't buy it. Select the "free" option (radio button) on the "buy" page. Then select "Social". After you sign up, you will get a fully functional JRebel license key. You can then download JRebel or use the key in your IDEs embedded version. The catch, (yes, there is a catch), you have to allow them to post on your behalf (advertise) once a month on your FB timeline or Twitter account. I gave them my twitter account, no biggie, I never use it and no one I know really uses it. So save $260.

Should URL be case sensitive?

Look at the specification here: section 2.7.3 http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-25#page-19

The scheme and host are case-insensitive and normally provided in lowercase; all other components are compared in a case-sensitive manner.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

HTML if image is not found

Try using border=0 in the img tag to make the ugly square go away.

<img src="someimage.png" border="0" alt="some alternate text" />

How to get an array of specific "key" in multidimensional array without looping

PHP 5.5+

Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.

PHP < 5.3

Wordpress 3.1+

In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.

PHP < 5.3

If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Omitting one Setter/Getter in Lombok

User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter and @Setter.

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;

Spring boot 2.3 version, this is working well.

ViewBag, ViewData and TempData

1)TempData

Allows you to store data that will survive for a redirect. Internally it uses the Session as backing store, after the redirect is made the data is automatically evicted. The pattern is the following:

public ActionResult Foo()
{
    // store something into the tempdata that will be available during a single redirect
    TempData["foo"] = "bar";

    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("bar");
}

public ActionResult Bar()
{
    var foo = TempData["foo"];
    ...
}

2)ViewBag, ViewData

Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request.

The pattern is the following:

public ActionResult Foo()
{
    ViewBag.Foo = "bar";
    return View();
}

and in the view:

@ViewBag.Foo

or with ViewData:

public ActionResult Foo()
{
    ViewData["Foo"] = "bar";
    return View();
}

and in the view:

@ViewData["Foo"]

ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3.

This being said, none of those two constructs should ever be used. You should use view models and strongly typed views. So the correct pattern is the following:

View model:

public class MyViewModel
{
    public string Foo { get; set; }
}

Action:

public Action Foo()
{
    var model = new MyViewModel { Foo = "bar" };
    return View(model);
}

Strongly typed view:

@model MyViewModel
@Model.Foo

After this brief introduction let's answer your question:

My requirement is I want to set a value in a controller one, that controller will redirect to ControllerTwo and Controller2 will render the View.

public class OneController: Controller
{
    public ActionResult Index()
    {
        TempData["foo"] = "bar";
        return RedirectToAction("index", "two");
    }
}

public class TwoController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Foo = TempData["foo"] as string
        };
        return View(model);
    }
}

and the corresponding view (~/Views/Two/Index.cshtml):

@model MyViewModel
@Html.DisplayFor(x => x.Foo)

There are drawbacks of using TempData as well: if the user hits F5 on the target page the data will be lost.

Personally I don't use TempData neither. It's because internally it uses Session and I disable session in my applications. I prefer a more RESTful way to achieve this. Which is: in the first controller action that performs the redirect store the object in your data store and user the generated unique id when redirecting. Then on the target action use this id to fetch back the initially stored object:

public class OneController: Controller
{
    public ActionResult Index()
    {
        var id = Repository.SaveData("foo");
        return RedirectToAction("index", "two", new { id = id });
    }
}

public class TwoController: Controller
{
    public ActionResult Index(string id)
    {
        var model = new MyViewModel
        {
            Foo = Repository.GetData(id)
        };
        return View(model);
    }
}

The view stays the same.

text-overflow: ellipsis not working

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631

Android Fragment handle back button press

Use addToBackStack method when replacing one fragment by another:

getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("my_fragment").commit();

Then in your activity, use the following code to go back from a fragment to another (the previous one).

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

SVN upgrade working copy

On MacOS:

  1. Get the latest compiled SVN client binaries from here.
  2. Install.
  3. Add binaries to path (the last installation screen explains how).
  4. Open terminal and run the following command on your project directory:

    svn upgrade

Test if element is present using Selenium WebDriver?

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception.

To check that an element is present, you could try this

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

This will return true if at least one element is found and false if it does not exist.

The official documentation recommends this method:

findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.

PHP: How to check if image file exists?

Read first 5 bytes form HTTP using fopen() and fread() then use this:

DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10)); 

to detect image.

how to implement login auth in node.js

I tried this answer and it didn't work for me. I am also a newbie on web development and took classes where i used mlab but i prefer parse which is why i had to look for the most suitable solution. Here is my own current solution using parse on expressJS.

1)Check if the user is authenticated: I have a middleware function named isLogginIn which I use on every route that needs the user to be authenticated:

 function isLoggedIn(req, res, next) {
 var currentUser = Parse.User.current();
 if (currentUser) {
     next()
 } else {
     res.send("you are not authorised");
 }
}

I use this function in my routes like this:

  app.get('/my_secret_page', isLoggedIn, function (req, res) 
  {
    res.send('if you are viewing this page it means you are logged in');
  });

2) The Login Route:

  // handling login logic
  app.post('/login', function(req, res) {
  Parse.User.enableUnsafeCurrentUser();
  Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
    res.redirect('/books');
  }, function(error) {
    res.render('login', { flash: error.message });
  });
});

3) The logout route:

 // logic route
  app.get("/logout", function(req, res){
   Parse.User.logOut().then(() => {
    var currentUser = Parse.User.current();  // this will now be null
    });
        res.redirect('/login');
   });

This worked very well for me and i made complete reference to the documentation here https://docs.parseplatform.org/js/guide/#users

Thanks to @alessioalex for his answer. I have only updated with the latest practices.

How to control size of list-style-type disc in CSS?

I am buliding up on Kolja's answer, to explain how viewBox works

The viewBox is a coordinate system.

Syntax: viewBox="posX posY width height"

viewBox="0 0 4 4" will create this coordinate system:

The yellow area is the visible area.

So if you like to center something in it, then you need to use viewBox='-2 -2 4 4'

Coordinate System

I know it looks completly retarded and I also don't understand why they designed it this way...

_x000D_
_x000D_
ul {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='-2 -2 4 4'><circle r='1' /></svg>");
}

.x {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='-2 -2 4 4'><circle r='.5' /></svg>");
}

.y {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='-3 -2 4 4'><circle r='.5' /></svg>");
}

.z {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='-3.5 -2 4 4'><circle r='.5' /></svg>");
}
_x000D_
Centered Circle (viewBox Method) [viewBox='-2 -2 4 4', circle r='1']:

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

Decrease Circle Radius [viewBox='-2 -2 4 4', circle r='.5']:

<ul class="x">
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

Move Circle Closer to Text [viewBox='-3 -2 4 4', circle r='.5']:

<ul class="y">
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

...even closer (use float values) [viewBox='-3.5 -2 4 4', circle r='.5']:

<ul class="z">
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>
_x000D_
_x000D_
_x000D_

But there is a much easier method, you can just use the circles cx and cy attributes.

_x000D_
_x000D_
.centered {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 100 100'><circle cx='50%' cy='50%' r='20' /></svg>");
}

.x {
  list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 100 100'><circle cx='50%' cy='50%' r='10' /></svg>");
}
_x000D_
Centered Circle (cx/xy) Radius 20 [viewBox='0 0 100 100', circle cx='50%' cy='50%' r='20']:

<ul class="centered_a">
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

Centered Circle (cx/xy) Radius 10 [viewBox='0 0 100 100', circle cx='50%' cy='50%' r='10']:

<ul class="x">
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>
_x000D_
_x000D_
_x000D_

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

Excel 2010: how to use autocomplete in validation list

Here's another option. It works by putting an ActiveX ComboBox on top of the cell with validation enabled, and then providing autocomplete in the ComboBox instead.

Option Explicit

' Autocomplete - replacing validation lists with ActiveX ComboBox
'
' Usage:
'   1. Copy this code into a module named m_autocomplete
'   2. Go to Tools / References and make sure "Microsoft Forms 2.0 Object Library" is checked
'   3. Copy and paste the following code to the worksheet where you want autocomplete
'      ------------------------------------------------------------------------------------------------------
'      - autocomplete
'      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'          m_autocomplete.SelectionChangeHandler Target
'      End Sub
'      Private Sub AutoComplete_Combo_KeyDown(ByVal KeyCode As msforms.ReturnInteger, ByVal Shift As Integer)
'          m_autocomplete.KeyDownHandler KeyCode, Shift
'      End Sub
'      Private Sub AutoComplete_Combo_Click()
'          m_autocomplete.AutoComplete_Combo_Click
'      End Sub
'      ------------------------------------------------------------------------------------------------------

' When the combobox is clicked, it should dropdown (expand)
Public Sub AutoComplete_Combo_Click()
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object
    If cbo.Visible Then cb.DropDown
End Sub

' Make it easier to navigate between cells
Public Sub KeyDownHandler(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Const UP As Integer = -1
    Const DOWN As Integer = 1

    Const K_TAB_______ As Integer = 9
    Const K_ENTER_____ As Integer = 13
    Const K_ARROW_UP__ As Integer = 38
    Const K_ARROW_DOWN As Integer = 40

    Dim direction As Integer: direction = 0

    If Shift = 0 And KeyCode = K_TAB_______ Then direction = DOWN
    If Shift = 0 And KeyCode = K_ENTER_____ Then direction = DOWN
    If Shift = 1 And KeyCode = K_TAB_______ Then direction = UP
    If Shift = 1 And KeyCode = K_ENTER_____ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_UP__ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_DOWN Then direction = DOWN

    If direction <> 0 Then ActiveCell.Offset(direction, 0).Activate

    AutoComplete_Combo_Click
End Sub

Public Sub SelectionChangeHandler(ByVal Target As Range)
    On Error GoTo errHandler

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object

    ' Try to hide the ComboBox. This might be buggy...
    If cbo.Visible Then
        cbo.Left = 10
        cbo.Top = 10
        cbo.ListFillRange = ""
        cbo.LinkedCell = ""
        cbo.Visible = False
        Application.ScreenUpdating = True
        ActiveSheet.Calculate
        ActiveWindow.SmallScroll
        Application.WindowState = Application.WindowState
        DoEvents
    End If

    If Not HasValidationList(Target) Then GoTo ex

    Application.EnableEvents = False

    ' TODO: the code below is a little fragile
    Dim lfr As String
    lfr = Mid(Target.Validation.Formula1, 2)
    lfr = Replace(lfr, "INDIREKTE", "") ' norwegian
    lfr = Replace(lfr, "INDIRECT", "") ' english
    lfr = Replace(lfr, """", "")
    lfr = Application.Range(lfr).Address(External:=True)

    cbo.ListFillRange = lfr
    cbo.Visible = True
    cbo.Left = Target.Left
    cbo.Top = Target.Top
    cbo.Height = Target.Height + 5
    cbo.Width = Target.Width + 15
    cbo.LinkedCell = Target.Address(External:=True)
    cbo.Activate
    cb.SelStart = 0
    cb.SelLength = cb.TextLength
    cb.DropDown

    GoTo ex

errHandler:
    Debug.Print "Error"
    Debug.Print Err.Number
    Debug.Print Err.Description
ex:
    Application.EnableEvents = True
End Sub

' Does the cell have a validation list?
Function HasValidationList(Cell As Range) As Boolean
    HasValidationList = False
    On Error GoTo ex
    If Cell.Validation.Type = xlValidateList Then HasValidationList = True
ex:
End Function

' Retrieve or create the ComboBox
Function GetComboBoxObject(ws As Worksheet) As OLEObject
    Dim cbo As OLEObject
    On Error Resume Next
    Set cbo = ws.OLEObjects("AutoComplete_Combo")
    On Error GoTo 0
    If cbo Is Nothing Then
        'Dim EnableSelection As Integer: EnableSelection = ws.EnableSelection
        Dim ProtectContents As Boolean: ProtectContents = ws.ProtectContents

        Debug.Print "Lager AutoComplete_Combo"
        If ProtectContents Then ws.Unprotect
        Set cbo = ws.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
                            Left:=50, Top:=18.75, Width:=129, Height:=18.75)
        cbo.name = "AutoComplete_Combo"
        cbo.Object.MatchRequired = True
        cbo.Object.ListRows = 12
        If ProtectContents Then ws.Protect
    End If
    Set GetComboBoxObject = cbo
End Function

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

Here's a simple working solution:

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

.elem:hover {
    -webkit-animation:spin 1.5s linear infinite;
    -moz-animation:spin 1.5s linear infinite;
    animation:spin 1.5s linear infinite;
}

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

Create session factory in Hibernate 4

Even there is an update in 4.3.0 API. ServiceRegistryBuilder is also deprecated in 4.3.0 and replaced with the StandardServiceRegistryBuilder. Now the actual code for creating the session factory would look this example on creating session factory.

Git error when trying to push -- pre-receive hook declined

I got this when trying to push to a dokku instance. Turns out the disk was full on my server.

Ran: du -f

And result was:

Filesystem      Size  Used Avail Use% Mounted on
udev            476M     0  476M   0% /dev
tmpfs           100M  4.4M   95M   5% /run
/dev/xvda1      7.8G  7.4G  8.9M 100% /

How to detect if CMD is running as Administrator/has elevated privileges?

Pretty much what others have put before, but as a one liner that can be put at the beginning of a batch command. (Well, usually after @echo off.)

net.exe session 1>NUL 2>NUL || (Echo This script requires elevated rights. & Exit /b 1)

Remove trailing newline from the elements of a string list

list comprehension? [x.strip() for x in lst]

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

Subset of rows containing NA (missing) values in a chosen column of a data frame

new_data <- data %>% filter_all(any_vars(is.na(.))) 

This should create a new data frame (new_data) with only the missing values in it.

Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).

How do I sort a table in Excel if it has cell references in it?

The answer for me was to separate the data into two grids with a blank column between them. The grid on the left is the data you want to be able to sort, the grid on the right contains the formula you want to calculate. When you sort, the formula simply work on the data in the rows in the left-hand grid and do not get the row references mixed up by the sort.

Split string into array

Do you care for non-English names? If so, all of the presented solutions (.split(''), [...str], Array.from(str), etc.) may give bad results, depending on language:

"????? ???????".split("") // the current president of India, Pranab Mukherjee
// returns ["?", "?", "?", "?", "?", " ", "?", "?", "?", "?", "?", "?", "?"]
// but should return ["??", "?", "?", "?", " ", "??", "?", "??", "??"]

Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

There is no way to identify the charset of a string that is completely accurate. There are ways to try to guess the charset. One of these ways, and probably/currently the best in PHP, is mb_detect_encoding(). This will scan your string and look for occurrences of stuff unique to certain charsets. Depending on your string, there may not be such distinguishable occurrences.

Take the ISO-8859-1 charset vs ISO-8859-15 ( http://en.wikipedia.org/wiki/ISO/IEC_8859-15#Changes_from_ISO-8859-1 )

There's only a handful of different characters, and to make it worse, they're represented by the same bytes. There is no way to detect, being given a string without knowing it's encoding, whether byte 0xA4 is supposed to signify ¤ or € in your string, so there is no way to know it's exact charset.

(Note: you could add a human factor, or an even more advanced scanning technique (e.g. what Oroboros102 suggests), to try to figure out based upon the surrounding context, if the character should be ¤ or €, though this seems like a bridge too far)

There are more distinguishable differences between e.g. UTF-8 and ISO-8859-1, so it's still worth trying to figure it out when you're unsure, though you can and should never rely on it being correct.

Interesting read: http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html#how-do-i-determine-the-charset-encoding-of-a-string

There are other ways of ensuring the correct charset though. Concerning forms, try to enforce UTF-8 as much as possible (check out snowman to make sure yout submission will be UTF-8 in every browser: http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen ) That being done, at least you're can be sure that every text submitted through your forms is utf_8. Concerning uploaded files, try running the unix 'file -i' command on it through e.g. exec() (if possible on your server) to aid the detection (using the document's BOM.) Concerning scraping data, you could read the HTTP headers, that usually specify the charset. When parsing XML files, see if the XML meta-data contain a charset definition.

Rather than trying to automagically guess the charset, you should first try to ensure a certain charset yourself where possible, or trying to grab a definition from the source you're getting it from (if applicable) before resorting to detection.

Spring cron expression for every after 30 minutes

According to the Quartz-Scheduler Tutorial It should be value="0 0/30 * * * ?"

The field order of the cronExpression is

1.Seconds

2.Minutes

3.Hours

4.Day-of-Month

5.Month

6.Day-of-Week

7.Year (optional field)

Ensure you have at least 6 parameters or you will get an error (year is optional)

MySQL FULL JOIN?

MySQL lacks support for FULL OUTER JOIN.

So if you want to emulate a Full join on MySQL take a look here .

A commonly suggested workaround looks like this:

SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
LEFT JOIN
        t_17
ON      t_13.value = t_17.value
UNION ALL
SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
RIGHT JOIN
        t_17
ON      t_13.value = t_17.value
WHERE   t_13.value IS NULL
ORDER BY
        COALESCE(val13, val17)
LIMIT 30

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

Android DialogFragment vs Dialog

DialogFragment is basically a Fragment that can be used as a dialog.

Using DialogFragment over Dialog due to the following reasons:

  • DialogFragment is automatically re-created after configuration changes and save & restore flow
  • DialogFragment inherits full Fragment’s lifecycle
  • No more IllegalStateExceptions and leaked window crashes. This was pretty common when the activity was destroyed with the Alert Dialog still there.

More detail

Set The Window Position of an application via command line

Bill K.'s answer was the most elegant if you just want to start a window at startup or start from a shortcut on the desktop.

Just open the window where you want it, right click and choose properties. select Layout uncheck "let system position window" and click OK.

Window will now open just where you want it. You can set font and window colors at the same time on other tabs. sweet.

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

PowerShell: Store Entire Text File Contents in Variable

To get the entire contents of a file:

$content = [IO.File]::ReadAllText(".\test.txt")

Number of lines:

([IO.File]::ReadAllLines(".\test.txt")).length

or

(gc .\test.ps1).length

Sort of hackish to include trailing empty line:

[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

How can I start PostgreSQL server on Mac OS X?

If you didn't install it with Homebrew and directly from the Mac package, this worked for me for PostgreSQL 12 when using all the default locations, variables, etc.

$ sudo su postgres
bash-3.2$ /Library/PostgreSQL/12/bin/pg_ctl -D /Library/PostgreSQL/12/data/ stop

How to check status of PostgreSQL server Mac OS X

You can use brew to start/stop pgsql. I've following short cuts in my ~/.bashrc file

alias start-pg='brew services start postgresql'
alias stop-pg='brew services stop postgresql'
alias restart-pg='brew services restart postgresql'

TypeError: 'undefined' is not a function (evaluating '$(document)')

Also check for including jQuery, followed by some components/other libraries (like jQuery UI) and then accidentially including jQuery again - this will redefine jQuery and drop the component helpers (like .datepicker) off the instance.

Format a JavaScript string using placeholders and an object of substitutions?

As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().

Placeholders:

  • %s String.
  • %d,%i Integer number.
  • %f Floating point number.
  • %o Object hyperlink.

e.g.

console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);

BTW, to see the output:

  • In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
  • In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.

@Update - nodejs support

Seems nodejs don't support %f, instead, could use %d in nodejs. With %d number will be printed as floating number, not just integer.

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I encountered some weird behaviour that did not reflect the actual code base so after some time trying several solutions, my problem was solved by manually deleting everything under /var/cache/tomcat8/

How can I make one python file run another?

  • you can run your .py file simply with this code:

import os 
os.system('python filename.py')

note: put the file in the same directory of your main python file.

Powershell command to hide user from exchange address lists

I use this as a daily scheduled task to hide users disabled in AD from the Global Address List

$mailboxes = get-user | where {$_.UserAccountControl -like '*AccountDisabled*' -and $_.RecipientType -eq 'UserMailbox' } | get-mailbox  | where {$_.HiddenFromAddressListsEnabled -eq $false}

foreach ($mailbox in $mailboxes) { Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $mailbox }

For homebrew mysql installs, where's my.cnf?

One way to find out:

sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf

How to convert Varchar to Int in sql server 2008?

That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.

UPDATE

Based on your comments I would remove any spaces that are in the values you are trying to convert.

Insert an item into sorted list in Python

Use the insort function of the bisect module:

import bisect 
a = [1, 2, 4, 5] 
bisect.insort(a, 3) 
print(a)

Output

[1, 2, 3, 4, 5] 

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Telling Python to save a .txt file to a certain directory on Windows and Mac

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

A bit late, but try this one.

function Set-Files($Path) {
    if(Test-Path $Path -PathType Leaf) {
        # Do any logic on file
        Write-Host $Path
        return
    }

    if(Test-Path $path -PathType Container) {
        # Do any logic on folder use exclude on get-childitem
        # cycle again
        Get-ChildItem -Path $path | foreach { Set-Files -Path $_.FullName }
    }
}

# call
Set-Files -Path 'D:\myFolder'

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

This worked on Sublime 3:


To browse html files with default app by Alt+L hotkey:

Add this line to Preferences -> Key Bindings - User opening file:

{ "keys": ["alt+l"], "command": "open_in_browser"}


To browse or open with external app like chrome:

Add this line to Tools -> Build System -> New Build System... opening file, and save with name "OpenWithChrome.sublime-build"

"shell_cmd": "C:\\PROGRA~1\\Google\\Chrome\\APPLIC~1\\chrome.exe $file"

Then you can browse/open the file by selecting Tools -> Build System -> OpenWithChrome and pressing F7 or Ctrl+B key.

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

Get key by value in dictionary

I realize it's been a long time and the original asker likely no longer has any need of an answer, but none of these are good answers if you actually have control over this code. You're just using the wrong data structure. This is a perfect illustration of the use case for a two-way dict:

>>> from collections import defaultdict, UserDict
>>> class TwoWayDict(UserDict):
...     def __init__(self, *args, **kwargs):
...         super().__init__(*args, **kwargs)
...         self.val_to_keys = defaultdict(list)
...     def __setitem__(self, key, value):
...         super().__setitem__(key, value)
...         self.val_to_keys[value].append(key)
...     def get_keys_for_val(self, value):
...         return self.val_to_keys[value]
... 
>>> d = TwoWayDict()
>>> d['a'] = 1
>>> d['b'] = 1
>>> d.get_keys_for_val(1)
['a', 'b']

Adds miniscule overhead to insertions but you keep constant-time lookup, except now in both directions. No need to construct the reverse mapping from scratch every time you need it. Just store it as you go and access it as needed.

Further, many of these answers are not even correct because clearly many people can have the same age but they're only returning the first matching key, not all of them.

How to move a marker in Google Maps API

use panTo(x,y).This will help u

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use below code to provide different color to actionbar text and actionbar background just use below theme in manifest against the activity in which you want output :)

<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/TitleBarTextColor</item>
    <item name="android:background">YOUR_COLOR_CODE</item>
</style>

<style name="TitleBarTextColor" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">YOUR_COLOR_CODE</item>
</style>