Programs & Examples On #Django

Django is an open source server-side web application framework, written in Python. It is designed to reduce the effort required to create complex data-driven websites and web applications, with a special focus on less code, no-redundancy and being more explicit than implicit.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

<script type='text/javascript'>

function foo() {


var user_choice = window.confirm('Would you like to continue?');


if(user_choice==true) {


window.location='your url';  // you can also use element.submit() if your input type='submit' 


} else {


return false;


}
}

</script>

<input type="button" onClick="foo()" value="save">

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Your code is

urlpatterns = [
    url(r'^$', 'myapp.views.home'),
    url(r'^contact/$', 'myapp.views.contact'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
]

change it to following as you're importing include() function :

urlpatterns = [
    url(r'^$', views.home),
    url(r'^contact/$', views.contact),
    url(r'^login/$', views.login),
]

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

How to get the current URL within a Django template?

The below code helps me:

 {{ request.build_absolute_uri }}

OperationalError, no such column. Django

This error can happen if you instantiate a class that relies on that table, for example in views.py.

Django error - matching query does not exist

You can use this:

comment = Comment.objects.filter(pk=comment_id)

'pip' is not recognized as an internal or external command

Most frequently it is:

in cmd.exe write

python -m pip install --user [name of your module here without brackets]

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

How to set True as default value for BooleanField on Django?

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

Select DISTINCT individual columns in django?

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

How can I get all the request headers in Django?

For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.

The source is a pretty good reference on how to accomplish what you are trying to do.

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

How to convert a Django QuerySet to a list

Why not just call .values('reqColumn1','reqColumn2') or .values_list('reqColumn1','reqColumn2') on the queryset?

answers_list = models.objects.values('reqColumn1','reqColumn2')

result = [{'reqColumn1':value1,'reqColumn2':value2}]

OR

answers_list = models.objects.values_list('reqColumn1','reqColumn2')

result = [(value1,value2)]

You can able to do all the operation on this QuerySet, which you do for list .

Django set field value after a form is initialized

in widget use 'value' attr. Example:

username = forms.CharField(
    required=False,
    widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
)

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

How can I temporarily disable a foreign key constraint in MySQL?

Instead of disabling your constraint, permanently modify it to ON DELETE SET NULL. That will accomplish a similar thing and you wouldn't have to turn key checking on and off. Like so:

ALTER TABLE tablename1 DROP FOREIGN KEY fk_name1; //get rid of current constraints
ALTER TABLE tablename2 DROP FOREIGN KEY fk_name2;

ALTER TABLE tablename1 
  ADD FOREIGN KEY (table2_id) 
        REFERENCES table2(id)
        ON DELETE SET NULL  //add back constraint

ALTER TABLE tablename2 
  ADD FOREIGN KEY (table1_id) 
        REFERENCES table1(id)
        ON DELETE SET NULL //add back other constraint

Have a read of this (http://dev.mysql.com/doc/refman/5.5/en/alter-table.html) and this (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html).

MySQL "incorrect string value" error when save unicode string in Django

You can change the collation of your text field to UTF8_general_ci and the problem will be solved.

Notice, this cannot be done in Django.

Django request.GET

Calling /search/ should result in "you submitted nothing", but calling /search/?q= on the other hand should result in "you submitted u''"

Browsers have to add the q= even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:

if request.GET.get('q'):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

How to set a value of a variable inside a template code?

Use the with statement.

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.

How to delete a record in Django models?

MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query

DELETE FROM my_models where id=1

Django auto_now and auto_now_add

If you alter your model class like this:

class MyModel(models.Model):
    time = models.DateTimeField(auto_now_add=True)
    time.editable = True

Then this field will show up in my admin change page

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Unable to import path from django.urls

My assumption you already have settings on your urls.py

from django.urls import path, include 
# and probably something like this 
    urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

and on your app you should have something like this blog/urls.py

 from django.urls import path

 from .views import HomePageView, CreateBlogView

 urlpatterns = [
   path('', HomePageView.as_view(), name='home'),
   path('post/', CreateBlogView.as_view(), name='add_blog')
 ]

if it's the case then most likely you haven't activated your environment try the following to activate your environment first pipenv shell if you still get the same error try this methods below

make sure Django is installed?? any another packages? i.e pillow try the following

pipenv install django==2.1.5 pillow==5.4.1

then remember to activate your environment

pipenv shell

after the environment is activated try running

python3 manage.py makemigrations

python3 manage.py migrate

then you will need to run

python3 manage.py runserver

I hope this helps

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')

How to debug in Django, the good way?

i highly suggest to use PDB.

import pdb
pdb.set_trace()

You can inspect all the variables values, step in to the function and much more. https://docs.python.org/2/library/pdb.html

for checking out the all kind of request,response and hits to database.i am using django-debug-toolbar https://github.com/django-debug-toolbar/django-debug-toolbar

Django - Static file not found

There could be only two things in settings.py which causes problems for you.

1) STATIC_URL = '/static/'

2)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

and your static files should lie under static directory which is in same directory as project's settings file.

Even then if your static files are not loading then reason is , you might have kept

DEBUG = False

change it to True (strictly for development only). In production just change STATICFILES_DIRS to whatever path where static files resides.

Retrieving a Foreign Key value with django-rest-framework serializers

Another thing you can do is to:

  • create a property in your Item model that returns the category name and
  • expose it as a ReadOnlyField.

Your model would look like this.

class Item(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, related_name='items')

    def __unicode__(self):
        return self.name

    @property
    def category_name(self):
        return self.category.name

Your serializer would look like this. Note that the serializer will automatically get the value of the category_name model property by naming the field with the same name.

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.ReadOnlyField()

    class Meta:
        model = Item

Set up a scheduled job?

A more modern solution (compared to Celery) is Django Q: https://django-q.readthedocs.io/en/latest/index.html

It has great documentation and is easy to grok. Windows support is lacking, because Windows does not support process forking. But it works fine if you create your dev environment using the Windows for Linux Subsystem.

How do I get the object if it exists, or None if it does not exist?

You can do it this way:

go  = Content.objects.filter(name="baby").first()

Now go variable could be either the object you want or None

Ref: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.first

OSError - Errno 13 Permission denied

supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id

Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id

then type

chown -R user-id:group-id .

Replace user-id and group-id

. at the end indicates current partition / repository

// chown -R 1001:1001 . (that was my case)

How can I check the size of a collection within a Django template?

You can try with:

{% if theList.object_list.count > 0 %}
    blah, blah...
{% else %}
    blah, blah....
{% endif %} 

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

I had a similar problem and the solution was in the right use of the '$' (end-of-string) character:

My main url.py looked like this (notice the $ character):

urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^$', include('card_purchase.urls' )),
]

and my url.py for my card_purchases app said:

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]

I used the '$' twice. So a simple change worked:

urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^cp/', include('card_purchase.urls' )),
]

Notice the change in the second url! My url.py for my card_purchases app looks like this:

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]

Apart from this, I can confirm that quotes around named urls are crucial!

Chaining multiple filter() in Django, is this a bug?

These two style of filtering are equivalent in most cases, but when query on objects base on ForeignKey or ManyToManyField, they are slightly different.

Examples from the documentation.

model
Blog to Entry is a one-to-many relation.

from django.db import models

class Blog(models.Model):
    ...

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    pub_date = models.DateField()
    ...

objects
Assuming there are some blog and entry objects here.
enter image description here

queries

Blog.objects.filter(entry__headline_contains='Lennon', 
    entry__pub_date__year=2008)
Blog.objects.filter(entry__headline_contains='Lennon').filter(
    entry__pub_date__year=2008)  
    

For the 1st query (single filter one), it match only blog1.

For the 2nd query (chained filters one), it filters out blog1 and blog2.
The first filter restricts the queryset to blog1, blog2 and blog5; the second filter restricts the set of blogs further to blog1 and blog2.

And you should realize that

We are filtering the Blog items with each filter statement, not the Entry items.

So, it's not the same, because Blog and Entry are multi-valued relationships.

Reference: https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
If there is something wrong, please correct me.

Edit: Changed v1.6 to v1.8 since the 1.6 links are no longer available.

Django Template Variables and Javascript

I have found we can pass Django variables to javascript functions like this:-

<button type="button" onclick="myJavascriptFunction('{{ my_django_variable }}')"></button>
<script>
    myJavascriptFunction(djangoVariable){
       alert(djangoVariable);
    }
</script>

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).earliest('check_in')

Or alternatively

Reserved.objects.filter(client=client_id).latest('-check_in')

Here is the documentations for earliest() and latest()

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

How do I perform query filtering in django templates

I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.

Some other possible solutions:

  1. Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.

  2. Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.

Is it bad to have my virtualenv directory inside my git repository?

If you know which operating systems your application will be running on, I would create one virtualenv for each system and include it in my repository. Then I would make my application detect which system it is running on and use the corresponding virtualenv.

The system could e.g. be identified using the platform module.

In fact, this is what I do with an in-house application I have written, and to which I can quickly add a new system's virtualenv in case it is needed. This way, I do not have to rely on that pip will be able to successfully download the software my application requires. I will also not have to worry about compilation of e.g. psycopg2 which I use.

If you do not know which operating system your application may run on, you are probably better off using pip freeze as suggested in other answers here.

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

Django Admin - change header 'Django administration' text

First of all, you should add templates/admin/base_site.html to your project. This file can safely be overwritten since it’s a file that the Django devs have intended for the exact purpose of customizing your admin site a bit. Here’s an example of what to put in the file:

{% extends "admin/base.html" %}
{% load i18n %}

{% block title %}{{ title }} | {% trans 'Some Organisation' %}{% endblock %}

{% block branding %}
<style type="text/css">
  #header
  {
    /* your style here */
  }
</style>
<h1 id="site-name">{% trans 'Organisation Website' %}</h1>
{% endblock %}

{% block nav-global %}{% endblock %}

This is common practice. But I noticed after this that I was still left with an annoying “Site Administration” on the main admin index page. And this string was not inside any of the templates, but rather set inside the admin view. Luckily it’s quite easy to change. Assuming your language is set to English, run the following commands from your project directory:

$ mkdir locale
$ ./manage.py makemessages -l en

Now open up the file locale/en/LC_MESSAGES/django.po and add two lines after the header information (the last two lines of this example)

"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2010-04-03 03:25+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

msgid "Site administration"
msgstr "Main administration index"

After this, remember to run the following command and reload your project’s server:

$ ./manage.py compilemessages

source: http://overtag.dk/wordpress/2010/04/changing-the-django-admin-site-title/

django import error - No module named core.management

If, like me, you are running your django in a virtualenv, and getting this error, look at your manage.py. The first line should define the python executable used to run the script. This should be the path to your virtualenv's python, but it is something wrong like /usr/bin/python, which is not the same path and will use the global python environment (and packages will be missing). Just change the path into the path to the python executable in your virtualenv.

You can also replace your shebang line with #!/usr/bin/env python. This should use the proper python environment and interpreter provided that you activate your virtualenv first (I assume you know how to do this).

Iterate over model instance field names and values in template

Ok, I know this is a bit late, but since I stumbled upon this before finding the correct answer so might someone else.

From the django docs:

# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
[<Blog: Beatles Blog>]

# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

How do I integrate Ajax with Django applications?

Easy ajax calls with Django

(26.10.2020)
This is in my opinion much cleaner and simpler than the correct answer. This one also includes how to add the csrftoken and using login_required methods with ajax.

The view

@login_required
def some_view(request):
    """Returns a json response to an ajax call. (request.user is available in view)"""
    # Fetch the attributes from the request body
    data_attribute = request.GET.get('some_attribute')  # Make sure to use POST/GET correctly
    # DO SOMETHING...
    return JsonResponse(data={}, status=200)

urls.py

urlpatterns = [
    path('some-view-does-something/', views.some_view, name='doing-something'),
]

The ajax call

The ajax call is quite simple, but is sufficient for most cases. You can fetch some values and put them in the data object, then in the view depicted above you can fetch their values again via their names.

You can find the csrftoken function in django's documentation. Basically just copy it and make sure it is rendered before your ajax call so that the csrftoken variable is defined.

$.ajax({
    url: "{% url 'doing-something' %}",
    headers: {'X-CSRFToken': csrftoken},
    data: {'some_attribute': some_value},
    type: "GET",
    dataType: 'json',
    success: function (data) {
        if (data) {
            console.log(data);
            // call function to do something with data
            process_data_function(data);
        }
    }
});

Add HTML to current page with ajax

This might be a bit off topic but I have rarely seen this used and it is a great way to minimize window relocations as well as manual html string creation in javascript.

This is very similar to the one above but this time we are rendering html from the response without reloading the current window.

If you intended to render some kind of html from the data you would receive as a response to the ajax call, it might be easier to send a HttpResponse back from the view instead of a JsonResponse. That allows you to create html easily which can then be inserted into an element.

The view

# The login required part is of course optional
@login_required
def create_some_html(request):
    """In this particular example we are filtering some model by a constraint sent in by 
    ajax and creating html to send back for those models who match the search"""
    # Fetch the attributes from the request body (sent in ajax data)
    search_input = request.GET.get('search_input')

    # Get some data that we want to render to the template
    if search_input:
        data = MyModel.objects.filter(name__contains=search_input) # Example
    else:
        data = []

    # Creating an html string using template and some data
    html_response = render_to_string('path/to/creation_template.html', context = {'models': data})

    return HttpResponse(html_response, status=200)

The html creation template for view

creation_template.html

{% for model in models %}
   <li class="xyz">{{ model.name }}</li>
{% endfor %}

urls.py

urlpatterns = [
    path('get-html/', views.create_some_html, name='get-html'),
]

The main template and ajax call

This is the template where we want to add the data to. In this example in particular we have a search input and a button that sends the search input's value to the view. The view then sends a HttpResponse back displaying data matching the search that we can render inside an element.

{% extends 'base.html' %}
{% load static %}
{% block content %}
    <input id="search-input" placeholder="Type something..." value="">
    <button id="add-html-button" class="btn btn-primary">Add Html</button>
    <ul id="add-html-here">
        <!-- This is where we want to render new html -->
    </ul>
{% end block %}

{% block extra_js %}
    <script>
        // When button is pressed fetch inner html of ul
        $("#add-html-button").on('click', function (e){
            e.preventDefault();
            let search_input = $('#search-input').val();
            let target_element = $('#add-html-here');
            $.ajax({
                url: "{% url 'get-html' %}",
                headers: {'X-CSRFToken': csrftoken},
                data: {'search_input': search_input},
                type: "GET",
                dataType: 'html',
                success: function (data) {
                    if (data) {
                        console.log(data);
                        // Add the http response to element
                        target_element.html(data);
                    }
                }
            });
        })
    </script>
{% endblock %}

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

If you get errors trying to install mysqlclient with pip, you may lack the mysql dev library. Install it by running:

apt-get install libmysqlclient-dev

and try again to install mysqlclient:

pip install mysqlclient

Using {% url ??? %} in django templates

I run into same problem.

What I found from documentation, we should use namedspace.

in your case {% url login:login_view %}

Proper way to handle multiple forms on one page in Django

if request.method == 'POST':
    expectedphraseform = ExpectedphraseForm(request.POST)
    bannedphraseform = BannedphraseForm(request.POST)
    if expectedphraseform.is_valid():
        expectedphraseform.save()
        return HttpResponse("Success")
    if bannedphraseform.is_valid():
        bannedphraseform.save()
        return HttpResponse("Success")
else:
    bannedphraseform = BannedphraseForm()
    expectedphraseform = ExpectedphraseForm()
return render(request, 'some.html',{'bannedphraseform':bannedphraseform, 'expectedphraseform':expectedphraseform})

This worked for me accurately as I wanted. This Approach has a single problem that it validates both the form's errors. But works Totally fine.

Django - after login, redirect user to his custom page --> mysite.com/username

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    name=request.user.username
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

Is it better to use path() or url() in urls.py for django 2.0?

From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows

from django.contrib import admin
from django.urls import path

from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^posts/$', post_home, name='post_home'),

]

where posts is an application & post_home is a function in views.py

How to override and extend basic Django admin templates?

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

Do you already have database entries in the table UserProfile? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL. Therefore it asks you what you want to set those fields in the column new_fields to. I had to delete all the rows from this table to solve the problem.

(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)

Django: save() vs update() to update the database?

Using update directly is more efficient and could also prevent integrity problems.

From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

e = Entry.objects.get(id=10)
e.comments_on = False
e.save()

…do this:

Entry.objects.filter(id=10).update(comments_on=False)

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

Django - Did you forget to register or load this tag?

You need to change:

{% endblock content %}

to

{% endblock %}

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

What is `related_name` used for in Django?

prefetch_related use for prefetch data for Many to many and many to one relationship data. select_related is to select data from a single value relationship. Both of these are used to fetch data from their relationships from a model. For example, you build a model and a model that has a relationship with other models. When a request comes you will also query for their relationship data and Django has very good mechanisms To access data from their relationship like book.author.name but when you iterate a list of models for fetching their relationship data Django create each request for every single relationship data. To overcome this we do have prefetchd_related and selected_related

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

Had a similar problem that resolved by adding both these two parameters to ForeignKey: null=True, on_delete=models.SET_NULL

How to 'bulk update' with Django?

Update:

Django 2.2 version now has a bulk_update.

Old answer:

Refer to the following django documentation section

Updating multiple objects at once

In short you should be able to use:

ModelClass.objects.filter(name='bar').update(name="foo")

You can also use F objects to do things like incrementing rows:

from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)

See the documentation.

However, note that:

  • This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
  • No django signals will be emitted.
  • You can't perform an .update() on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter() and .exclude() methods.

How to properly use the "choices" field option in Django

I would suggest to use django-model-utils instead of Django built-in solution. The main advantage of this solution is the lack of string declaration duplication. All choice items are declared exactly once. Also this is the easiest way for declaring choices using 3 values and storing database value different than usage in source code.

from django.utils.translation import ugettext_lazy as _
from model_utils import Choices

class MyModel(models.Model):
   MONTH = Choices(
       ('JAN', _('January')),
       ('FEB', _('February')),
       ('MAR', _('March')),
   )
   # [..]
   month = models.CharField(
       max_length=3,
       choices=MONTH,
       default=MONTH.JAN,
   )

And with usage IntegerField instead:

from django.utils.translation import ugettext_lazy as _
from model_utils import Choices

class MyModel(models.Model):
   MONTH = Choices(
       (1, 'JAN', _('January')),
       (2, 'FEB', _('February')),
       (3, 'MAR', _('March')),
   )
   # [..]
   month = models.PositiveSmallIntegerField(
       choices=MONTH,
       default=MONTH.JAN,
   )
  • This method has one small disadvantage: in any IDE (eg. PyCharm) there will be no code completion for available choices (it’s because those values aren’t standard members of Choices class).

Django: Display Choice Value

It looks like you were on the right track - get_FOO_display() is most certainly what you want:

In templates, you don't include () in the name of a method. Do the following:

{{ person.get_gender_display }}

Error: No module named psycopg2.extensions

In python 3.4, while in a virtual environment, make sure you have the build dependencies first:

sudo apt-get build-dep python3-psycopg2

Then install it:

pip install psycopg2 

How to set the timezone in Django?

Choose a valid timezone from the tzinfo database. They tend to take the form e.g. Africa/Gaborne and US/Eastern

Find the one which matches the city nearest you, or the one which has your timezone, then set your value of TIME_ZONE to match.

Setting the selected value on a Django forms.ChoiceField

I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.

Django MEDIA_URL and MEDIA_ROOT

(at least) for Django 1.8:

If you use

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

if settings.DEBUG:
    urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

urlpatterns.append(url(r'$', 'views.home', name='home')),

What does on_delete do on Django models?

CASCADE will also delete the corresponding field connected with it.

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

How to compare two JSON objects with the same elements in a different order equal?

Another way could be to use json.dumps(X, sort_keys=True) option:

import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison

This works for nested dictionaries and lists.

React Error: Target Container is not a DOM Element

Also you can do something like that:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


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 %}

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

How do I perform HTML decoding/encoding using Python/Django?

Searching the simplest solution of this question in Django and Python I found you can use builtin theirs functions to escape/unescape html code.

Example

I saved your html code in scraped_html and clean_html:

scraped_html = (
    '&lt;img class=&quot;size-medium wp-image-113&quot; '
    'style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; '
    'src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; '
    'alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;'
)
clean_html = (
    '<img class="size-medium wp-image-113" style="margin-left: 15px;" '
    'title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" '
    'alt="" width="300" height="194" />'
)

Django

You need Django >= 1.0

unescape

To unescape your scraped html code you can use django.utils.text.unescape_entities which:

Convert all named and numeric character references to the corresponding unicode characters.

>>> from django.utils.text import unescape_entities
>>> clean_html == unescape_entities(scraped_html)
True

escape

To escape your clean html code you can use django.utils.html.escape which:

Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.

>>> from django.utils.html import escape
>>> scraped_html == escape(clean_html)
True

Python

You need Python >= 3.4

unescape

To unescape your scraped html code you can use html.unescape which:

Convert all named and numeric character references (e.g. &gt;, &#62;, &x3e;) in the string s to the corresponding unicode characters.

>>> from html import unescape
>>> clean_html == unescape(scraped_html)
True

escape

To escape your clean html code you can use html.escape which:

Convert the characters &, < and > in string s to HTML-safe sequences.

>>> from html import escape
>>> scraped_html == escape(clean_html)
True

Getting the SQL from a Django QuerySet

As an alternative to the other answers, django-devserver outputs SQL to the console.

How can I see the raw SQL queries Django is running?

Take a look at debug_toolbar, it's very useful for debugging.

Documentation and source is available at http://django-debug-toolbar.readthedocs.io/.

Screenshot of debug toolbar

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

Extending the User model with custom fields in Django

Try this:

Create a model called Profile and reference the user with a OneToOneField and provide an option of related_name.

models.py

from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
        if created:
            Profile.objects.create(user=instance).save()
    except Exception as err:
        print('Error creating user profile!')

Now to directly access the profile using a User object you can use the related_name.

views.py

from django.http import HttpResponse

def home(request):
    profile = f'profile of {request.user.user_profile}'
    return HttpResponse(profile)

When saving, how can you check if a field has changed?

Another late answer, but if you're just trying to see if a new file has been uploaded to a file field, try this: (adapted from Christopher Adams's comment on the link http://zmsmith.com/2010/05/django-check-if-a-field-has-changed/ in zach's comment here)

Updated link: https://web.archive.org/web/20130101010327/http://zmsmith.com:80/2010/05/django-check-if-a-field-has-changed/

def save(self, *args, **kw):
    from django.core.files.uploadedfile import UploadedFile
    if hasattr(self.image, 'file') and isinstance(self.image.file, UploadedFile) :
        # Handle FileFields as special cases, because the uploaded filename could be
        # the same as the filename that's already there even though there may
        # be different file contents.

        # if a file was just uploaded, the storage model with be UploadedFile
        # Do new file stuff here
        pass

What is the path that Django uses for locating and loading templates?

I also had issues with this part of the tutorial (used tutorial for version 1.7).

My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.

This is the line from django/contrib/admin/templates/admin/base_site.html:

<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>

But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).

Example manual:

<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>

Render HTML to PDF in Django site

After trying to get this to work for too many hours, I finally found this: https://github.com/vierno/django-xhtml2pdf

It's a fork of https://github.com/chrisglass/django-xhtml2pdf that provides a mixin for a generic class-based view. I used it like this:

    # views.py
    from django_xhtml2pdf.views import PdfMixin
    class GroupPDFGenerate(PdfMixin, DetailView):
        model = PeerGroupSignIn
        template_name = 'groups/pdf.html'

    # templates/groups/pdf.html
    <html>
    <style>
    @page { your xhtml2pdf pisa PDF parameters }
    </style>
    </head>
    <body>
        <div id="header_content"> (this is defined in the style section)
            <h1>{{ peergroupsignin.this_group_title }}</h1>
            ...

Use the model name you defined in your view in all lowercase when populating the template fields. Because its a GCBV, you can just call it as '.as_view' in your urls.py:

    # urls.py (using url namespaces defined in the main urls.py file)
    url(
        regex=r"^(?P<pk>\d+)/generate_pdf/$",
        view=views.GroupPDFGenerate.as_view(),
        name="generate_pdf",
       ),

How do I clone a Django model instance object and save it to the database?

There's a clone snippet here, which you can add to your model which does this:

def clone(self):
  new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
  return self.__class__.objects.create(**new_kwargs)

Django - "no module named django.core.management"

You can try it like so : python3 manage.py migrate (make sur to be in the src/ directory)

You can also try with pip install -r requirements.txt (make sur you see the requirements.txt file when you type ls after the migrate

If after all it still won't work try pip install django

Hope it helps

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

Make sure you're passing a selector to jQuery, not some form of data:

$( '.my-selector' )

not:

$( [ 'my-data' ] )

How to send a correct authorization header for basic authentication

PHP - curl:

$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...

PHP - POST in WordPress:

$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")
  )
));
...

In Django, how do I check if a user is in a certain group?

If you don't need the user instance on site (as I did), you can do it with

User.objects.filter(pk=userId, groups__name='Editor').exists()

This will produce only one request to the database and return a boolean.

How to create Password Field in Model Django

I thinks it is vary helpful way.

models.py

from django.db import models
class User(models.Model):
    user_name = models.CharField(max_length=100)
    password = models.CharField(max_length=32)

forms.py

from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
    class Meta:
        model= User
        fields=[
           'user_name',
           'password'
            ]
       widgets = {
      'password': forms.PasswordInput()
         }

How to find pg_config path

Works for me by installing the first the following pip packages: libpq-dev and postgresql-common

Best practice for Django project working directory structure

My answer is inspired on my own working experience, and mostly in the book Two Scoops of Django which I highly recommend, and where you can find a more detailed explanation of everything. I just will answer some of the points, and any improvement or correction will be welcomed. But there also can be more correct manners to achieve the same purpose.

Projects
I have a main folder in my personal directory where I maintain all the projects where I am working on.

Source Files
I personally use the django project root as repository root of my projects. But in the book is recommended to separate both things. I think that this is a better approach, so I hope to start making the change progressively on my projects.

project_repository_folder/
    .gitignore
    Makefile
    LICENSE.rst
    docs/
    README.rst
    requirements.txt
    project_folder/
        manage.py
        media/
        app-1/
        app-2/
        ...
        app-n/
        static/
        templates/
        project/
            __init__.py
            settings/
                __init__.py
                base.py
                dev.py
                local.py
                test.py
                production.py
            ulrs.py
            wsgi.py

Repository
Git or Mercurial seem to be the most popular version control systems among Django developers. And the most popular hosting services for backups GitHub and Bitbucket.

Virtual Environment
I use virtualenv and virtualenvwrapper. After installing the second one, you need to set up your working directory. Mine is on my /home/envs directory, as it is recommended on virtualenvwrapper installation guide. But I don't think the most important thing is where is it placed. The most important thing when working with virtual environments is keeping requirements.txt file up to date.

pip freeze -l > requirements.txt 

Static Root
Project folder

Media Root
Project folder

README
Repository root

LICENSE
Repository root

Documents
Repository root. This python packages can help you making easier mantaining your documentation:

Sketches

Examples

Database

How to convert Django Model object to dict with its fields and values?

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

def as_dict(self):
    return dict((f.name, getattr(self, f.name)) for f in self._meta.fields)

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()])

AttributeError: 'module' object has no attribute 'model'

I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.

Django CSRF Cookie Not Set

Problem seems that you are not handling GET requests appropriately or directly posting the data without first getting the form.

When you first access the page, client will send GET request, in that case you should send html with appropriate form.

Later, user fills up the form and sends POST request with form data.

Your view should be:

def deposit(request,account_num):
   if request.method == 'POST':
      form_=AccountForm(request.POST or None, instance=account)
      if form.is_valid(): 
          #handle form data
          return HttpResponseRedirect("/history/" + account_num + "/")
      else:
         #handle when form not valid
    else:
       #handle when request is GET (or not POST)
       form_=AccountForm(instance=account)

    return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

Does Django scale?

Check out this micro news aggregator called EveryBlock.

It's entirely written in Django. In fact they are the people who developed the Django framework itself.

Django Server Error: port is already in use

ps aux | grep manage

ubuntu 3438 127.0.0 2.3 40256 14064 pts/0 T 06:47 0:00 python manage.py runserver

kill -9 3438

Django, creating a custom 500/404 error page

Django 3.0

here is link how to customize error views

here is link how to render a view

in the urls.py (the main one, in project folder), put:

handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'

and in that app (my_app_name) put in the views.py:

def custom_page_not_found_view(request, exception):
    return render(request, "errors/404.html", {})

def custom_error_view(request, exception=None):
    return render(request, "errors/500.html", {})

def custom_permission_denied_view(request, exception=None):
    return render(request, "errors/403.html", {})

def custom_bad_request_view(request, exception=None):
    return render(request, "errors/400.html", {})

NOTE: error/404.html is the path if you place your files into the projects (not the apps) template foldertemplates/errors/404.html so please place the files where you want and write the right path.

NOTE 2: After page reload, if you still see the old template, change in settings.py DEBUG=True, save it, and then again to False (to restart the server and collect the new files).

How to check Django version

The most pythonic way I've seen to get the version of any package:

>>> import pkg_resources;
>>> pkg_resources.get_distribution('django').version
'1.8.4'

This ties directly into setup.py: https://github.com/django/django/blob/master/setup.py#L37

Also there is distutils to compare the version:

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("2.3.1") > StrictVersion("10.1.2")
False

As for getting the python version, I agree with James Bradbury:

>>> import sys
>>> sys.version
'3.4.3 (default, Jul 13 2015, 12:18:23) \n[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]'

Tying it all together:

>>> StrictVersion((sys.version.split(' ')[0])) > StrictVersion('2.6')
True

django templates: include and extends

When you use the extends template tag, you're saying that the current template extends another -- that it is a child template, dependent on a parent template. Django will look at your child template and use its content to populate the parent.

Everything that you want to use in a child template should be within blocks, which Django uses to populate the parent. If you want use an include statement in that child template, you have to put it within a block, for Django to make sense of it. Otherwise it just doesn't make sense and Django doesn't know what to do with it.

The Django documentation has a few really good examples of using blocks to replace blocks in the parent template.

https://docs.djangoproject.com/en/dev/ref/templates/language/#template-inheritance

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Can't install via pip because of egg_info error

I was trying to install pyautogui and followed instructions from the first answer but was unsuccessful. The difference for me was running pip install pillow and then running pip install pyautogui

I don't know what this means, but I hope this helps some people out.

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

How to get the currently logged in user's user id in Django?

You can access Current logged in user by using the following code:

request.user.id

Why does DEBUG=False setting make my django Static Files Access fail?

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

My solution is just small correction to Conrado solution above.

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

How to see docker image contents

EXPLORING DOCKER IMAGE!

  1. Figure out what kind of shell is in there bash or sh...

Inspect the image first: docker inspect name-of-container-or-image

Look for entrypoint or cmd in the JSON return.

  1. Then do: docker run --rm -it --entrypoint=/bin/bash name-of-image

once inside do: ls -lsa or any other shell command like: cd ..

The -it stands for interactive... and TTY. The --rm stands for remove container after run.

If there are no common tools like ls or bash present and you have access to the Dockerfile simple add the common tool as a layer.
example (alpine Linux):

RUN apk add --no-cache bash

And when you don't have access to the Dockerfile then just copy/extract the files from a newly created container and look through them:

docker create <image>  # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah

Getting the SQL from a Django QuerySet

As an alternative to the other answers, django-devserver outputs SQL to the console.

Cannot download Docker images behind a proxy

Your APT proxy settings are not related to Docker.

Docker uses the HTTP_PROXY environment variable, if present. For example:

sudo HTTP_PROXY=http://192.168.1.1:3128/ docker pull busybox

But instead, I suggest you have a look at your /etc/default/dockerconfiguration file: you should have a line to uncomment (and maybe adjust) to get your proxy settings applied automatically. Then restart the Docker server:

service docker restart

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:

var value = ($("#text").val()).replace(".", ":");

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

How to open the Google Play Store directly from my Android application?

If you want to open Google Play store from your app then use this command directy: market://details?gotohome=com.yourAppName, it will open your app's Google Play store pages.

Show all apps by a specific publisher

Search for apps that using the Query on its title or description

Reference: https://tricklio.com/market-details-gotohome-1/

Handler vs AsyncTask vs Thread

It depends which one to chose is based on the requirement

Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread

If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper

AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance

Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.

Remove leading or trailing spaces in an entire column of data

I've found that the best (and easiest) way to delete leading, trailing (and excessive) spaces in Excel is to use a third-party plugin. I've been using ASAP Utilities for Excel and it accomplishes the task as well as adds many other much-needed features. This approach doesn't require writing formulas and can remove spaces on any selection spanning multiple columns and/or rows. I also use this to sanitize and remove the uninvited non-breaking space that often finds its way into Excel data when copying-and-pasting from other Microsoft products.

More information regarding ASAP Utilities and trimming can be found here:

http://www.asap-utilities.com/asap-utilities-excel-tools-tip.php?tip=87enter image description here

Pass data from Activity to Service using an Intent

If you are using kotlin you can try the following code,

In the sending activity,

  val intent = Intent(context, RecorderService::class.java);
  intent.putExtra("filename", filename);
  context.startService(intent)

In the service,

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)

    if (intent != null && intent.extras != null)
       val filename = intent.getStringExtra("filename")

}

Set Response Status Code

As written before, but for beginner like me don't forget to include the return.

$this->response->statusCode(200);
return $this->response;

How do I change an HTML selected option using JavaScript?

You can use JQuery also

$(document).ready(function () {
  $('#personlist').val("10");
}

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

Since it sounds like your JAVA_HOME variable is not set correctly, follow the instructions for setting that.

Setting JAVA_HOME environment variable on MAC OSX 10.9

I would imagine once you set this, it will stop complaining.

What is the purpose of backbone.js?

Here's an interesting presentation:

An intro to Backbone.js

Hint (from the slides):

  • Rails in the browser? No.
  • An MVC framework for JavaScript? Sorta.
  • A big fat state machine? YES!

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

SyntaxError: expected expression, got '<'

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.

Limiting the output of PHP's echo to 200 characters

It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'

$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

You can build it manually:

var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();

and to force two digits on the values that require it, you can use something like this:

("0000" + 5).slice(-2)

Which would look like this:

_x000D_
_x000D_
var m = new Date();_x000D_
var dateString =_x000D_
    m.getUTCFullYear() + "/" +_x000D_
    ("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +_x000D_
    ("0" + m.getUTCDate()).slice(-2) + " " +_x000D_
    ("0" + m.getUTCHours()).slice(-2) + ":" +_x000D_
    ("0" + m.getUTCMinutes()).slice(-2) + ":" +_x000D_
    ("0" + m.getUTCSeconds()).slice(-2);_x000D_
_x000D_
console.log(dateString);
_x000D_
_x000D_
_x000D_

Can I add an image to an ASP.NET button?

You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.

Style="background-image:url('Image/1.png');"

You can change image location with using

background-repeat

properties. So you can write a button like below:

<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>

Delete all objects in a list

Here's how you delete every item from a list.

del c[:]

Here's how you delete the first two items from a list.

del c[:2]

Here's how you delete a single item from a list (a in your case), assuming c is a list.

del c[0]

How to delete object?

You can use extension methods to achive this.

public static ObjRemoverExtension {
    public static void DeleteObj<T>(this T obj) where T: new()
    {
        obj = null;
    }
}

And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()

EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.

CSS media query to target only iOS devices

Short answer No. CSS is not specific to brands.

Below are the articles to implement for iOS using media only.

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

http://stephen.io/mediaqueries/

Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance

http://www.kevinleary.net/php-detect-ios-mobile-users/

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

How to justify navbar-nav in Bootstrap 3

Hi you can use this below code for working justified nav

<div class="navbar navbar-inverse">
    <ul class="navbar-nav nav nav-justified">
        <li class="active"><a href="#">Inicio</a></li>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
        <li><a href="#">Item 4</a></li>
    </ul>
 </div>

Postgres and Indexes on Foreign Keys and Primary Keys

I love how this is explained in the article Cool performance features of EclipseLink 2.5

Indexing Foreign Keys

The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.

Convert web page to image

Somebody wrote a blog post about this a few years back. There are examples in several languages, using both WebKit and Mozilla. There's also an example in Ruby.

It boils down to this: decide how wide you want your window to be; put a browser component in the window; wait until the page loads; capture the pixel buffer contents.

Run CSS3 animation only once (at page loading)

I just got this working on Firefox and Chrome. You just add/remove the below class accordingly to your needs.

.animateOnce {
  -webkit-animation: NAME-OF-YOUR-ANIMATION 0.5s normal forwards; 
  -moz-animation:    NAME-OF-YOUR-ANIMATION 0.5s normal forwards;
  -o-animation:      NAME-OF-YOUR-ANIMATION 0.5s normal forwards;
}

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

Merge development branch with master

This is how I usually do it. First, sure that you are ready to merge your changes into master.

  1. Check if development is up to date with the latest changes from your remote server with a git fetch
  2. Once the fetch is completed git checkout master.
  3. Ensure the master branch has the latest updates by executing git pull
  4. Once the preparations have been completed, you can start the merge with git merge development
  5. Push the changes with git push -u origin master and you are done.

You can find more into about git merging in the article.

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

Deleting multiple columns based on column names in Pandas

You can just pass the column names as a list with specifying the axis as 0 or 1

  • axis=1: Along the Rows
  • axis=0: Along the Columns
  • By default axis=0

    data.drop(["Colname1","Colname2","Colname3","Colname4"],axis=1)

Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

ImageView in circular through xml

This is the simplest way that I designed. Try this.

dependencies

  • implementation 'androidx.appcompat:appcompat:1.3.0-beta01'

  • implementation 'androidx.cardview:cardview:1.0.0'

     <android.support.v7.widget.CardView
         android:layout_width="80dp"
         android:layout_height="80dp"
         android:elevation="12dp"
         android:id="@+id/view2"
        app:cardCornerRadius="40dp"
         android:layout_centerHorizontal="true"
         android:innerRadius="0dp"
         android:shape="ring"
         android:thicknessRatio="1.9">
         <ImageView
             android:layout_height="80dp"
             android:layout_width="match_parent"
             android:id="@+id/imageView1"
             android:src="@drawable/YOUR_IMAGE"
             android:layout_alignParentTop="true"
             android:layout_centerHorizontal="true">
         </ImageView>
      </android.support.v7.widget.CardView>
    

    If you are working on android versions above lollipop

     <android.support.v7.widget.CardView
     android:layout_width="80dp"
     android:layout_height="80dp"
     android:elevation="12dp"
     android:id="@+id/view2"
     app:cardCornerRadius="40dp"
     android:layout_centerHorizontal="true">
     <ImageView
         android:layout_height="80dp"
         android:layout_width="match_parent"
         android:id="@+id/imageView1"
         android:src="@drawable/YOUR_IMAGE"
         android:scaleType="centerCrop"/>
       </android.support.v7.widget.CardView>
    

Adding Border to round ImageView - LATEST VERSION

Wrap it with another CardView slightly bigger than the inner one and set its background color to add a border to your round image. You can increase the size of the outer CardView to increase the thickness of the border.

<androidx.cardview.widget.CardView
  android:layout_width="155dp"
  android:layout_height="155dp"
  app:cardCornerRadius="250dp"
  app:cardBackgroundColor="@color/white">

    <androidx.cardview.widget.CardView
      android:layout_width="150dp"
      android:layout_height="150dp"
      app:cardCornerRadius="250dp"
      android:layout_gravity="center">

        <ImageView
          android:layout_width="150dp"
          android:layout_height="150dp"
          android:src="@drawable/default_user"
          android:scaleType="centerCrop"/>

   </androidx.cardview.widget.CardView>

 </androidx.cardview.widget.CardView>

How to use bluetooth to connect two iPhone?

Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.

As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide

How can I check whether Google Maps is fully loaded?

Where the variable map is an object of type GMap2:

    GEvent.addListener(map, "tilesloaded", function() {
      console.log("Map is fully loaded");
    });

How to find Port number of IP address?

If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.

If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.

If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.

How to watch for array changes?

Not sure if this covers absolutely everything, but I use something like this (especially when debugging) to detect when an array has an element added:

var array = [1,2,3,4];
array = new Proxy(array, {
    set: function(target, key, value) {
        if (Number.isInteger(Number(key)) || key === 'length') {
            debugger; //or other code
        }
        target[key] = value;
        return true;
    }
});

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

How would you implement an LRU cache in Java?

Here's my own implementation to this problem

simplelrucache provides threadsafe, very simple, non-distributed LRU caching with TTL support. It provides two implementations:

  • Concurrent based on ConcurrentLinkedHashMap
  • Synchronized based on LinkedHashMap

You can find it here: http://code.google.com/p/simplelrucache/

What's the difference between IFrame and Frame?

IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.

All this means is that you should trust whatever you include in an iFrame or a regular frame.

Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).

Undefined index with $_POST

I know that this is old post but someone can help:

function POST($index, $default=NULL){
        if(isset($_POST[$index]))
        {
            if(!empty(trim($_POST[$index])))    
                return $_POST[$index];
        }
        return $default;
    }

This code above are my basic POST function what I use anywhere. Here you can put filters, regular expressions, etc. Is faster and clean. My advanced POST function is more complicate to accept and check arrays, string type, default values etc. Let's your imagination work here.

You easy can check username like this:

$username = POST("username");
if($username!==null){
    echo "{$username} is in the house.";
}

Also I added $default string that you can define some default value if POST is not active or content not exists.

echo "<h1>".POST("title", "Stack Overflow")."</h1>";

Play with it.

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

I had this issue, because .git/config contained worktree = D:/git-repositories/OldName. I just changed it into worktree = D:/git-repositories/NewName

I discovered that, because I used git gui, which showed a more detailed error message:

git gui error

How to call a method in another class in Java?

Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");

You have to add the class' and at a point like

yourClassNameWhereTheMethodIs.theMethodsName();

I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Python to print out status bar and percentage

Per Steven C. Howell's comment on Mark Rushakoff's answer

j = (i + 1) / n
stdout.write('\r')
stdout.write('[%-20s] %d%%' % ('='*int(20*j), 100*j))
stdout.flush()

where i is the current item and n is the total number of items

Using ls to list directories and their total sizes

I ran into an issue similar to what Martin Wilde described, in my case comparing the same directory on two different servers after mirroring with rsync.

Instead of using a script I added the -b flag to the du which counts the size in bytes and as far as I can determine eliminated the differences on the two servers. You still can use -s -h to get a comprehensible output.

iPhone: How to get current milliseconds?

I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime has the least overhead by a small margin. timeIntervalSince1970 is far slower than the others, probably due to NSDate instantiation overhead, though it may not matter for many use cases.

I'd recommend CACurrentMediaTime if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday if portability is a priority for you.

iPhone 4S

CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call

iPad 3

CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

How to autowire RestTemplate using annotations

Add the @Configuration annotation in the RestTemplateSOMENAME which extends the RestTemplate class.

@Configuration         
public class RestTemplateClass extends RestTemplate {

}

Then in your controller class you can use the Autowired annotation as follows.

@Autowired   
RestTemplateClass restTemplate;

Define make variable at rule execution time

A relatively easy way of doing this is to write the entire sequence as a shell script.

out.tar:
   set -e ;\
   TMP=$$(mktemp -d) ;\
   echo hi $$TMP/hi.txt ;\
   tar -C $$TMP cf $@ . ;\
   rm -rf $$TMP ;\

I have consolidated some related tips here: https://stackoverflow.com/a/29085684/86967

CSS text-overflow in a table cell?

In case you don't want to set fixed width to anything

The solution below allows you to have table cell content that is long, but must not affect the width of the parent table, nor the height of the parent row. For example where you want to have a table with width:100% that still applies auto-size feature to all other cells. Useful in data grids with "Notes" or "Comment" column or something.

enter image description here

Add these 3 rules to your CSS:

.text-overflow-dynamic-container {
    position: relative;
    max-width: 100%;
    padding: 0 !important;
    display: -webkit-flex;
    display: -moz-flex;
    display: flex;
    vertical-align: text-bottom !important;
}
.text-overflow-dynamic-ellipsis {
    position: absolute;
    white-space: nowrap;
    overflow-y: visible;
    overflow-x: hidden;
    text-overflow: ellipsis;
    -ms-text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    max-width: 100%;
    min-width: 0;
    width:100%;
    top: 0;
    left: 0;
}
.text-overflow-dynamic-container:after,
.text-overflow-dynamic-ellipsis:after {
    content: '-';
    display: inline;
    visibility: hidden;
    width: 0;
}

Format HTML like this in any table cell you want dynamic text overflow:

<td>
  <span class="text-overflow-dynamic-container">
    <span class="text-overflow-dynamic-ellipsis" title="...your text again for usability...">
      //...your long text here...
    </span>
  </span>
</td>

Additionally apply desired min-width (or none at all) to the table cell.

Of course the fiddle: https://jsfiddle.net/9wycg99v/23/

Python String and Integer concatenation

for i in range[1,10]: 
  string = "string" + str(i)

The str(i) function converts the integer into a string.

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

How to check whether a pandas DataFrame is empty?

To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:

if len(df.columns) == 0: 1

Reason:

According to the Pandas Reference API, there is a distinction between:

  • an empty dataframe with 0 rows and 0 columns
  • an empty dataframe with rows containing NaN hence at least 1 column

Arguably, they are not the same. The other answers are imprecise in that df.empty, len(df), or len(df.index) make no distinction and return index is 0 and empty is True in both cases.

Examples

Example 1: An empty dataframe with 0 rows and 0 columns

In [1]: import pandas as pd
        df1 = pd.DataFrame()
        df1
Out[1]: Empty DataFrame
        Columns: []
        Index: []

In [2]: len(df1.index)  # or len(df1)
Out[2]: 0

In [3]: df1.empty
Out[3]: True

Example 2: A dataframe which is emptied to 0 rows but still retains n columns

In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df2
Out[4]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

In [5]: df2 = df2[df2['AA'] == 5]
        df2
Out[5]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

In [6]: len(df2.index)  # or len(df2)
Out[6]: 0

In [7]: df2.empty
Out[7]: True

Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.

In [8]: len(df1.columns)
Out[8]: 0

In [9]: len(df2.columns)
Out[9]: 2

Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.

Why it matters

Let's add a new column to these dataframes to understand the implications:

# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
         df1
Out[10]:    CC
         0 111
         1 222
         2 333
In [11]: len(df1.columns)
Out[11]: 1

# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
         df2
Out[12]:    AA  BB   CC
         0 NaN NaN  111
         1 NaN NaN  222
         2 NaN NaN  333
In [13]: len(df2.columns)
Out[13]: 3

It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns) to see if a dataframe is empty.

Practical solution

# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df
Out[1]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
        df
Out[2]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2

# And accordingly, the other answers on this page
In [4]: len(df.index)  # or len(df)
Out[4]: 0

In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0:  # <--- here
            # Do something, e.g. 
            # drop any columns containing rows with `NaN`
            # to make the df really empty
            df = df.dropna(how='all', axis=1)
        df
Out[6]: Empty DataFrame
        Columns: []
        Index: []

# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0

Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN):

In [8]: df['CC'] = [111, 222, 333]
         df
Out[8]:    CC
         0 111
         1 222
         2 333
In [9]: len(df.columns)
Out[9]: 1

How do I get the localhost name in PowerShell?

A slight tweak on @CPU-100's answer, for the local FQDN:

[System.Net.DNS]::GetHostByName($Null).HostName

How to get multiple selected values of select box in php?

Use the following program for select the multiple values from select box.

multi.php

<?php
print <<<_HTML_
<html>
        <body>
                <form method="post" action="value.php">
                        <select name="flower[ ]" multiple>
                                <option value="flower">FLOWER</option>
                                <option value="rose">ROSE</option>
                                <option value="lilly">LILLY</option>
                                <option value="jasmine">JASMINE</option>
                                <option value="lotus">LOTUS</option>
                                <option value="tulips">TULIPS</option>
                        </select>
                        <input type="submit" name="submit" value=Submit>
                </form>
        </body>
</html>
_HTML_

?>

value.php

<?php
foreach ($_POST['flower'] as $names)
{
        print "You are selected $names<br/>";
}

?>

Is there a simple way to remove multiple spaces in a string?

I have to agree with Paul McGuire's comment. To me,

' '.join(the_string.split())

is vastly preferable to whipping out a regex.

My measurements (Linux and Python 2.5) show the split-then-join to be almost five times faster than doing the "re.sub(...)", and still three times faster if you precompile the regex once and do the operation multiple times. And it is by any measure easier to understand -- much more Pythonic.

How to quietly remove a directory with content in PowerShell

To delete content without a folder you can use the following:

Remove-Item "foldertodelete\*" -Force -Recurse

How to close activity and go back to previous activity in android

You can go back to the previous activity by just calling finish() in the activity you are on. Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this.

If you want to return results to activity one then when starting activity two you need:

startActivityForResults(myIntent, MY_REQUEST_CODE);

Inside your called activity you can then get the Intent from the onCreate() parameter or used

getIntent();

To set return a result to activity one then in activity two do

setResult(Activity.RESULT_OK, MyIntentToReturn);

If you have no intent to return then just say

setResult(Activity.RESULT_OK);

If the the activity has bad results you can use Activity.RESULT_CANCELED (this is used by default). Then in activity one you do

onActivityResult(int requestCode, int resultCode, Intent data) {
    // Handle the logic for the requestCode, resultCode and data returned...
}

To finish activity two use the same methods with finish() as described above with your results already set.

How to access nested elements of json object using getJSONArray method

I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());
    }
}

class Response {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;
    }

    public void setMap(MapNode map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }

    @Override
    public String toString() {
        return Arrays.toString(entry.toArray());
    }
}

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return "[key=" + key + ", value=" + value + "]";
    }
}

class Key {

    @SerializedName("$")
    private String value;

    @SerializedName("@xsi.type")
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "[value=" + value + ", type=" + type + "]";
    }
}

Program output:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]

If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".

How to check if a file is empty in Bash?

@geedoubleya answer is my favorite.

However, I do prefer this

if [[ -f diff.txt && -s diff.txt ]]
then
  rm -f empty.txt
  touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
  rm -f full.txt
  touch empty.txt
else
  echo "File diff.txt does not exist"
fi

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

// I usually do this:

x = "0" ;

if (!!+x) console.log('I am true');
else      console.log('I am false');

// Essentially converting string to integer and then boolean.

How do I compile jrxml to get jasper?

Using iReport designer 5.6.0, if you wish to compile multiple jrxml files without previewing - go to Tools -> Massive Processing Tool. Select Elaboration Type as "Compile Files", select the folder where all your jrxml reports are stored, and compile them in a batch.

Which header file do you include to use bool type in c in linux?

Try this header file in your code

stdbool.h

This must work

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

This is a simple task. You can follow the following steps.

  1. Create a folder in your solution and name it Reports.
  2. Add an ASP.Net web form and name it ReportView.aspx
  3. Create a Class ReportData and add it to the Reports folder. Add the following code to the Class.

    public class ReportData  
    {  
        public ReportData()  
        {  
            this.ReportParameters = new List<Parameter>();  
            this.DataParameters = new List<Parameter>();  
        }
    
        public bool IsLocal { get; set; }
        public string ReportName { get; set; }
        public List<Parameter> ReportParameters { get; set; }
        public List<Parameter> DataParameters { get; set; }
    }
    
    public class Parameter  
    {  
        public string ParameterName { get; set; }  
        public string Value { get; set; }  
    }
    
  4. Add another Class and name it ReportBasePage.cs. Add the following code in this Class.

    public class ReportBasePage : System.Web.UI.Page
    {
        protected ReportData ReportDataObj { get; set; }
    
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (HttpContext.Current != null)
                if (HttpContext.Current.Session["ReportData"] != null)
                {
                    ReportDataObj = HttpContext.Current.Session["ReportData"] as ReportData;
                    return;
                }
            ReportDataObj = new ReportData();
            CaptureRouteData(Page.Request);
        }
    
    
        private void CaptureRouteData(HttpRequest request)
        {
            var mode = (request.QueryString["rptmode"] + "").Trim();
            ReportDataObj.IsLocal = mode == "local" ? true : false;
            ReportDataObj.ReportName = request.QueryString["reportname"] + "";
            string dquerystr = request.QueryString["parameters"] + "";
            if (!String.IsNullOrEmpty(dquerystr.Trim()))
            {
                var param1 = dquerystr.Split(',');
                foreach (string pm in param1)
                {
                    var rp = new Parameter();
                    var kd = pm.Split('=');
                    if (kd[0].Substring(0, 2) == "rp")
                    {
                        rp.ParameterName = kd[0].Replace("rp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.ReportParameters.Add(rp);
                    }
                    else if (kd[0].Substring(0, 2) == "dp")
                    {
                        rp.ParameterName = kd[0].Replace("dp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.DataParameters.Add(rp);
                    }
                }
            }
        }
    }
    
  5. Add ScriptManager to the ReportView.aspx page. Now add a Report Viewer to the page. In report viewer set the property AsyncRendering="false". The code is given below.

        <rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
            Width="1271px" Height="1000px" >
        </rsweb:ReportViewer>
    
  6. Add two NameSpace in ReportView.aspx.cs

    using Microsoft.Reporting.WebForms;
    using System.IO;
    
  7. Change the System.Web.UI.Page to ReportBasePage. Just replace your code using the following.

    public partial class ReportView : ReportBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RenderReportModels(this.ReportDataObj);
            }
        }
    
        private void RenderReportModels(ReportData reportData)
        {
            // This is the Data Access Layer from which a method is called to fill data to the list.
            RASolarERPData dal = new RASolarERPData();
            List<ClosingInventoryValuation> objClosingInventory = new List<ClosingInventoryValuation>();
    
            // Reset report properties.
            ReportViewerRSFReports.Height = Unit.Parse("100%");
            ReportViewerRSFReports.Width = Unit.Parse("100%");
            ReportViewerRSFReports.CssClass = "table";
    
            // Clear out any previous datasources.
            this.ReportViewerRSFReports.LocalReport.DataSources.Clear();
    
            // Set report mode for local processing.
            ReportViewerRSFReports.ProcessingMode = ProcessingMode.Local;
    
            // Validate report source.
            var rptPath = Server.MapPath(@"./Report/" + reportData.ReportName +".rdlc");
    
            //@"E:\RSFERP_SourceCode\RASolarERP\RASolarERP\Reports\Report\" + reportData.ReportName + ".rdlc";
            //Server.MapPath(@"./Report/ClosingInventory.rdlc");
    
            if (!File.Exists(rptPath))
                return;
    
            // Set report path.
            this.ReportViewerRSFReports.LocalReport.ReportPath = rptPath;
    
            // Set report parameters.
            var rpPms = ReportViewerRSFReports.LocalReport.GetParameters();
            foreach (var rpm in rpPms)
            {
                var p = reportData.ReportParameters.SingleOrDefault(o => o.ParameterName.ToLower() == rpm.Name.ToLower());
                if (p != null)
                {
                    ReportParameter rp = new ReportParameter(rpm.Name, p.Value);
                    ReportViewerRSFReports.LocalReport.SetParameters(rp);
                }
            }
    
            //Set data paramater for report SP execution
            objClosingInventory = dal.ClosingInventoryReport(this.ReportDataObj.DataParameters[0].Value);
    
            // Load the dataSource.
            var dsmems = ReportViewerRSFReports.LocalReport.GetDataSourceNames();
            ReportViewerRSFReports.LocalReport.DataSources.Add(new ReportDataSource(dsmems[0], objClosingInventory));
    
            // Refresh the ReportViewer.
            ReportViewerRSFReports.LocalReport.Refresh();
        }
    }
    
  8. Add a Folder to the Reports Folder and name it Report. Now add a RDLC report to the Reports/Report folder and name it ClosingInventory.rdlc.

  9. Now add a Controller and name it ReportController. In the controller add the following action method.

    public ActionResult ReportViewer()
        {                
            ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
    
            return View();
        }
    
  10. Add a view page click on the ReportViewer Controller. Name the view page ReportViewer.cshtml. Add the following code to the view page.

    @using (Html.BeginForm("Login"))
     { 
           @Html.DropDownList("ddlYearMonthFormat", new SelectList(ViewBag.YearMonthFormat, "YearMonthValue",
     "YearMonthName"), new { @class = "DropDown" })
    
    Stock In Transit: @Html.TextBox("txtStockInTransit", "", new { @class = "LogInTextBox" })
    
    <input type="submit" onclick="return ReportValidationCheck();" name="ShowReport"
                     value="Show Report" />
    
    }
    
  11. Add an Iframe. Set the property of the Iframe as follows

    frameborder="0"  width="1000"; height="1000"; style="overflow:hidden;"
    scrolling="no"
    
  12. Add Following JavaScript to the viewer.

    function ReportValidationCheck() {
    
        var url = $('#hdUrl').val();
        var yearmonth = $('#ddlYearMonthFormat').val();      
        var stockInTransit = $('#txtStockInTransit').val()
    
        if (stockInTransit == "") {
            stockInTransit = 0;
        }
    
        if (yearmonth == "0") {
            alert("Please Select Month Correctly.");
        }
        else {
    
            //url = url + "dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            url = "../Reports/ReportView.aspx?rptmode=local&reportname=ClosingInventory&parameters=dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            var myframe = document.getElementById("ifrmReportViewer");
            if (myframe !== null) {
                if (myframe.src) {
                    myframe.src = url;
                }
                else if (myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
                    myframe.contentWindow.location = url;
                }
                else { myframe.setAttribute('src', url); }
            }
        }
    
        return false;
    }
    
  13. Web.config file add the following key to the appSettings section

    add key="UnobtrusiveJavaScriptEnabled" value="true"
    
  14. In system.web handlers Section add the following key

    add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    
  15. Change your data source to your own. This solution is very simple and I think every one will enjoy it.

Is it possible to set ENV variables for rails development environment in my code?

[Update]

While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
    end
  end
end

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"
end

Don't forget to restart the server so the configuration is reloaded!

[Old Answer]

For app-wide configuration, you might consider a solution like the following:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
facebook:
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes ERB.new, your YAML file can contain ERB markup.)

No submodule mapping found in .gitmodule for a path that's not a submodule

After looking at my .gitmodules, it turned out I did have an uppercase letter where I should not have. So keep in mind, the .gitmodules directories are case sensitive

Read specific columns from a csv file with csv module?

import pandas as pd 
csv_file = pd.read_csv("file.csv") 
column_val_list = csv_file.column_name._ndarray_values

Running Bash commands in Python

According to the error you are missing a package named swap on the server. This /usr/bin/cwm requires it. If you're on Ubuntu/Debian, install python-swap using aptitude.

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

Passing JavaScript array to PHP through jQuery $.ajax

I know it may be too late to answer this, but this worked for me in a great way:

  1. Stringify your javascript object (json) with var st = JSON.stringify(your_object);

  2. Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... });

  3. Decode your data on the server-side processing: $data = json_decode($_POST['data']);

That's it... you can freely use your data.

Multi-dimensional arrays and single arrays are handled as normal arrays. To access them just do the normal $foo[4].

Associative arrays (javsacript objects) are handled as php objects (classes). To access them just do it like classes: $foo->bar.

how to add jquery in laravel project

You can link libraries from cdn (Content delivery network):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.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>

Or link libraries locally, add css files in the css folder and jquery in js folder. You have to keep both folders in the laravel public folder then you can link like below:

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

If you link js files and css files locally (like in the last two examples) you need to add js and css files to the js and css folders which are in public\js or public\css not in resources\assets.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

One of the reasons for me getting an error was the file name make sure the file name is Dockerfile So i figured it out, hope it might help someone.

Fake "click" to activate an onclick method

I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:

var oElement = document.getElementById('elementId');   // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference

function clickHandler() {
    // this function will be called whenever the element is clicked
    // and can also be called from the context of other functions
}

Now, whenever this element is clicked, the code in clickHandler will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler to handle events triggered by other elements)>

Getting all names in an enum as a String[]

Another ways :

First one

Arrays.asList(FieldType.values())
            .stream()
            .map(f -> f.toString())
            .toArray(String[]::new);

Other way

Stream.of(FieldType.values()).map(f -> f.toString()).toArray(String[]::new);

how to enable sqlite3 for php?

The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:

cd /etc/php5/conf.d

cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D

sudo /etc/init.d/apache2 restart

Java, How to specify absolute value and square roots

int currentNum = 5;
double sqrRoot = 0.0;
int sqrRootInt = 0;



sqrRoot=Math.sqrt(currentNum);
sqrRootInt= (int)sqrRoot;

How to set image to fit width of the page using jsPDF?

A better solution is to set the doc width/height using the aspect ratio of your image.

_x000D_
_x000D_
var ExportModule = {_x000D_
  // Member method to convert pixels to mm._x000D_
  pxTomm: function(px) {_x000D_
    return Math.floor(px / $('#my_mm').height());_x000D_
  },_x000D_
  ExportToPDF: function() {_x000D_
    var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
    html2canvas(myCanvas, {_x000D_
      onrendered: function(canvas) {_x000D_
        var imgData = canvas.toDataURL(_x000D_
          'image/jpeg', 1.0);_x000D_
        //Get the original size of canvas/image_x000D_
        var img_w = canvas.width;_x000D_
        var img_h = canvas.height;_x000D_
_x000D_
        //Convert to mm_x000D_
        var doc_w = ExportModule.pxTomm(img_w);_x000D_
        var doc_h = ExportModule.pxTomm(img_h);_x000D_
        //Set doc size_x000D_
        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
        //set image height similar to doc size_x000D_
        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
        var currentTime = new Date();_x000D_
        doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
  Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
_x000D_
_x000D_

How to access to the parent object in c#

I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!

I would solve this with events/handlers.

public class Meter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production();
        _production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
        _production.DoSomething();
    }
}

public class Production
{
    protected int RequestPowerRating()
    {
        if (OnRequestPowerRating == null)
            throw new Exception("OnRequestPowerRating handler is not assigned");

        return OnRequestPowerRating();
    }

    public void DoSomething()
    {
        int powerRating = RequestPowerRating();
        Debug.WriteLine("The parents powerrating is :" + powerRating);

    }

    public Func<int> OnRequestPowerRating;
}

In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).


But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:

public interface IMeter
{
    int PowerRating { get; }
}

public class Meter : IMeter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production(this);
        _production.DoSomething();
    }

    public int PowerRating { get { return _powerRating; } }
}

public class Production
{
    private IMeter _meter;

    public Production(IMeter meter)
    {
        _meter = meter;
    }

    public void DoSomething()
    {
        Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
    }
}

This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.


Regards, Jeroen van Langen.

move_uploaded_file gives "failed to open stream: Permission denied" error

You can also run this script to find out the Apache process owner:

<?php echo exec('whoami'); ?>

And then change the owner of the destination directory to what you've got. Use the command:

chown user destination_dir

And then use the command

chmod 755 destination_dir

to change the destination directory permission.

Cannot attach the file *.mdf as database

Ran into this issue. Caused in my case by deleting the .mdf while iispexress was still running and therefor still using the DB. Right click on iisexpress in system tray and click exit THEN delete the MDF to prevent this error from actually occurring.

To fix this error simply within VS right click the App-Data folder add new item > SQL Server Database. Name: [use the database name provided by the update-database error] Click Add.

How can I edit a view using phpMyAdmin 3.2.4?

To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:

  1. Run the following query: SHOW CREATE VIEW your_view_name
  2. Expand the options and choose Full Texts
  3. Press Go
  4. Copy entire contents of the Create View column.
  5. Make changes to the query in the editor of your choice
  6. Run the query directly (without the CREATE VIEW... syntax) to make sure it runs as you expect it to.
  7. Once you're satisfied, click on your view in the list on the left to browse its data and then scroll all the way to the bottom where you'll see a CREATE VIEW link. Click that.
  8. Place a check in the OR REPLACE field.
  9. In the VIEW name put the name of the view you are going to update.
  10. In the AS field put the contents of the query that you ran while testing (without the CREATE VIEW... syntax).
  11. Press Go

I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.

form serialize javascript (no framework)

I've grabbed the entries() method of formData from @moison answer and from MDN it's said that :

The FormData.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The key of each pair is a USVString object; the value either a USVString, or a Blob.

but the only issue is that mobile browser (android and safari are not supported ) and IE and Safari desktop too

but basically here is my approach :

let theForm =  document.getElementById("contact"); 

theForm.onsubmit = function(event) {
    event.preventDefault();

    let rawData = new FormData(theForm);
    let data = {};

   for(let pair of rawData.entries()) {
     data[pair[0]] = pair[1]; 
    }
    let contactData = JSON.stringify(data);
    console.warn(contactData);
    //here you can send a post request with content-type :'application.json'

};

the code can be found here

Java: Enum parameter in method

I like this a lot better. reduces the if/switch, just do.

private enum Alignment { LEFT, RIGHT;

void process() {
//Process it...
} 
};    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  align.process();
}

of course, it can be:

String process(...) {
//Process it...
} 

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

How to stick a footer to bottom in css?

I had a similar issue with this sticky footer tutorial. If memory serves, you need to put your form tags within your <div class=Main /> section since the form tag itself causes issues with the lineup.

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

jQuery get input value after keypress

This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added.

Note that, if your element #dSuggest is the same as input:text[name=dSuggest] you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id of another element is not a good idea).

$('#dSuggest').keypress(function() {
    var dInput = this.value;
    console.log(dInput);
    $(".dDimension:contains('" + dInput + "')").css("display","block");
});

Can't run Curl command inside my Docker Container

curl: command not found

is a big hint, you have to install it with :

apt-get update; apt-get install curl

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

Quick way to retrieve user information Active Directory

You can simplify this code to:

        DirectorySearcher searcher = new DirectorySearcher();
        searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";

        SearchResultCollection results = searcher.FindAll();

        if (results.Count == 1)
        {
            //do what you want to do
        }
        else if (results.Count == 0)
        {
            //user does not exist
        }
        else
        {
            //found more than one user
            //something is wrong
        }

If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.

You should also use objectCategory instead of objectClass since objectCategory is indexed by default.

You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

PostgreSQL: How to change PostgreSQL user password?

To change password using Linux command line, use:

sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

Best way to concatenate List of String objects?

Your approach is dependent on Java's ArrayList#toString() implementation.

While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).

Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The CP1 means 'Code Page 1' - technically this translates to code page 1252

Google Maps API: open url by clicking on marker

url isn't an object on the Marker class. But there's nothing stopping you adding that as a property to that class. I'm guessing whatever example you were looking at did that too. Do you want a different URL for each marker? What happens when you do:

for (var i = 0; i < locations.length; i++) 
{
    var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png',
      new google.maps.Size(17, 19),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 19));
    var place = locations[i];
    var myLatLng = new google.maps.LatLng(place[1], place[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: flag,
        shape: shape,
        title: place[0],
        zIndex: place[3],
        url: "/your/url/"
    });

    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
}

Checking if an object is null in C#

You can try like below

public List<Object> dataList;
public  bool AddData(ref Object data)
bool success = false;
try
{
    if (data != null)
    {
       dataList.Add(data);
       success = doOtherStuff(data);
    }
}
catch (Exception e)
{
    throw new Exception(e.ToString());
}
return success;

}

How to show two figures using matplotlib?

You should call plt.show() only at the end after creating all the plots.

How to use orderby with 2 fields in linq?

Use ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

You can also use query syntax and say:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

What is the difference between functional and non-functional requirements?

Functional requirements

  1. Functional requirements specifies a function that a system or system component must be able to perform. It can be documented in various ways. The most common ones are written descriptions in documents, and use cases.

  2. Use cases can be textual enumeration lists as well as diagrams, describing user actions. Each use case illustrates behavioural scenarios through one or more functional requirements. Often, though, an analyst will begin by eliciting a set of use cases, from which the analyst can derive the functional requirements that must be implemented to allow a user to perform each use case.

  3. Functional requirements is what a system is supposed to accomplish. It may be

    • Calculations
    • Technical details
    • Data manipulation
    • Data processing
    • Other specific functionality
  4. A typical functional requirement will contain a unique name and number, a brief summary, and a rationale. This information is used to help the reader understand why the requirement is needed, and to track the requirement through the development of the system.

Non-functional requirements

LBushkin have already explained more about Non-functional requirements. I will add more.

  1. Non-functional requirements are any other requirement than functional requirements. This are the requirements that specifies criteria that can be used to judge the operation of a system, rather than specific behaviours.

  2. Non-functional requirements are in the form of "system shall be ", an overall property of the system as a whole or of a particular aspect and not a specific function. The system's overall properties commonly mark the difference between whether the development project has succeeded or failed.

  3. Non-functional requirements - can be divided into two main categories:

    • Execution qualities, such as security and usability, which are observable at run time.
    • Evolution qualities, such as testability, maintainability, extensibility and scalability, which are embodied in the static structure of the software system.
  4. Non-functional requirements place restrictions on the product being developed, the development process, and specify external constraints that the product must meet.
  5. The IEEE-Std 830 - 1993 lists 13 non-functional requirements to be included in a Software Requirements Document.
  1. Performance requirements
  2. Interface requirements
  3. Operational requirements
  4. Resource requirements
  5. Verification requirements
  6. Acceptance requirements
  7. Documentation requirements
  8. Security requirements
  9. Portability requirements
  10. Quality requirements
  11. Reliability requirements
  12. Maintainability requirements
  13. Safety requirements

Whether or not a requirement is expressed as a functional or a non-functional requirement may depend:

  • on the level of detail to be included in the requirements document
  • the degree of trust which exists between a system customer and a system developer.

Ex. A system may be required to present the user with a display of the number of records in a database. This is a functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the number needs to be updated in real time, the system architects must ensure that the system is capable of updating the [displayed] record count within an acceptably short interval of the number of records changing.

References:

  1. Functional requirement
  2. Non-functional requirement
  3. Quantification and Traceability of Requirements

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

Border Radius of Table is not working

This is my solution using the wrapper, just removing border-collapse might not be helpful always, because you might want to have borders.

_x000D_
_x000D_
.wrapper {_x000D_
  overflow: auto;_x000D_
  border-radius: 6px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border-style: hidden;_x000D_
_x000D_
  width:100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Column 1</th>_x000D_
        <th>Column 2</th>_x000D_
        <th>Column 3</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>Foo Bar boo</td>_x000D_
        <td>Lipsum</td>_x000D_
        <td>Beehuum Doh</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Dolor sit</td>_x000D_
        <td>ahmad</td>_x000D_
        <td>Polymorphism</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Kerbalium</td>_x000D_
        <td>Caton, gookame kyak</td>_x000D_
        <td>Corona Premium Beer</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

This article helped: https://css-tricks.com/table-borders-inside/

Optional Parameters in Go?

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

Disable vertical scroll bar on div overflow: auto

These two CSS properties can be used to hide the scrollbars:

overflow-y: hidden; // hide vertical
overflow-x: hidden; // hide horizontal

django MultiValueDictKeyError error, how do I deal with it

Use the MultiValueDict's get method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.

is_private = request.POST.get('is_private', False)

Generally,

my_var = dict.get(<key>, <default>)

How to make a local variable (inside a function) global

Simply declare your variable outside any function:

globalValue = 1

def f(x):
    print(globalValue + x)

If you need to assign to the global from within the function, use the global statement:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

Location of the android sdk has not been setup in the preferences in mac os?

Simply create this folder:

C:\Users\xxxxx\android-sdk\tools

and then from Window -> Preferences -> Android, put this path:

 C:\Users\xxxxx\android-sdk

Preventing an image from being draggable or selectable without using JS

I created a div element which has the same size as the image and is positioned on top of the image. Then, the mouse events do not go to the image element.

How to convert XML to java.util.Map and vice versa

How about XStream? Not 1 class but 2 jars for many use cases including yours, very simple to use yet quite powerful.

Downloading a file from spring controllers

I was able to stream line this by using the built in support in Spring with it's ResourceHttpMessageConverter. This will set the content-length and content-type if it can determine the mime-type

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}

Invoking a jQuery function after .each() has completed

what about

$(parentSelect).nextAll().fadeOut(200, function() { 
    $(this).remove(); 
}).one(function(){
    myfunction();
}); 

C# Change A Button's Background Color

WinForm:

private void button1_Click(object sender, EventArgs e)
{
   button2.BackColor = Color.Red;
}

WPF:

private void button1_Click(object sender, RoutedEventArgs e)
{
   button2.Background = Brushes.Blue;
}

The infamous java.sql.SQLException: No suitable driver found

You will get this same error if there is not a Resource definition provided somewhere for your app -- most likely either in the central context.xml, or individual context file in conf/Catalina/localhost. And if using individual context files, beware that Tomcat freely deletes them anytime you remove/undeploy the corresponding .war file.

How would you make two <div>s overlap?

If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:

#logo {
    float: left;
    margin: 0 10px 10px 20px;
}

#content {
    margin: 10px 0 0 10px;
}

or whatever margin you want.

How to remove newlines from beginning and end of a string?

I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.

To remove newlines from the beginning:

// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);

System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");

and end of a string:

// Trim right
String z = "\n\nfrom the end\n\n";

System.out.println("-" + z.split("\\n+$", 2)[0] + "-");

I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.

Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.

How to check string length with JavaScript

_x000D_
_x000D_
function cool(d)_x000D_
{_x000D_
    alert(d.value.length);_x000D_
}
_x000D_
<input type="text" value="" onblur="cool(this)">
_x000D_
_x000D_
_x000D_

It will return the length of string

Instead of blur use keydown event.

How to get complete current url for Cakephp

I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:

$this->params['url'];

While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL's. For example, we have the current URL:

projects/edit/6

And we want to append a custom parameter action called c_action with a value of remove_image, one could make use of $this->params['url]; and merge it with an array of custom parameter key => value pairs:

echo $this->Html->link('remove image', array_merge($this->params['url'], array('c_action' => 'remove_image'));

Using the above method we are able to append our custom parameters to the link and not cause a long chain on parameters to build up on the URL, because $this->params['url] only ever returns the controll action URL.

In the above example we'd need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:

echo $this->Html->link('remove image', array_merge($this->params['url'], array($id,'c_action' => 'remove_image'));

Where $is is a the ID of the project and you would have assigned it to the variable $id at controller level. The new URL will then be:

projects/edit/6/c_action:remove_image

Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is the case for me. Simply removing resulted in another error. I followed the steps of this post except the last one. For your convenience, I copied the 4 steps from the post that I followed to solve the problem as following:

  1. Right click on the edmx file, select Open with, XML editor
  2. Locate the entity in the edmx:StorageModels element
  3. Remove the DefiningQuery entirely
  4. Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)

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

Try using Database SetInitializer which belongs to using System.Data.Entity;

In Global.asax

protected void Application_Start()
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<yourContext>());
}

This will create new database everytime your model is changed.But your database would be empty.In order to fill it with dummy data you can use Seeding. Which you can implement as :

Seeding ::

protected void Application_Start()
{
    Database.SetInitializer(new AddressBookInitializer());
                ----rest code---
}
public class AddressBookInitializer : DropCreateDatabaseIfModelChanges<AddressBook>
{
    protected override void Seed(AddressBook context)
    {
        context.yourmodel.Add(
        {

        });
        base.Seed(context);
    }

}

Export DataBase with MySQL Workbench with INSERT statements

If you want to export just single table, or subset of data from some table, you can do it directly from result window:

  1. Click export button: enter image description here

  2. Change Save as type to "SQL Insert statements" enter image description here

JavaScript, getting value of a td with id name

If by 'td value' you mean text inside of td, then:

document.getElementById('td-id').innerHTML

Selenium WebDriver can't find element by link text

The problem might be in the rest of the html, the part that you didn't post.

With this example (I just closed the open tags):

<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
    <p>
    <strong class="ng-binding">Smoke Sequential</strong>
    </p>
    </div>
</div>
</a>

I was able to find the element without trouble with:

driver.findElement(By.linkText("Smoke Sequential")).click();

If there is more text inside the element, you could try a find by partial link text:

driver.findElement(By.partialLinkText("Sequential")).click();

Counting repeated elements in an integer array

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    int[] numbers=new int[5];
    String x=null;
    System.out.print("enter the number 10:"+"/n");
    for(int i=0;i<5;i++){
        numbers[i] = input.nextInt();
    }
    System.out.print("Numbers  :  count"+"\n");
    int count=1;
    Arrays.sort(numbers);
    for(int z=0;z<5;z++){
        for(int j=0;j<z;j++){
            if(numbers[z]==numbers[j] & j!=z){
                count=count+1;
            }
        }
        System.out.print(numbers[z]+" - "+count+"\n");
        count=1;

    }

Xcode 10 Error: Multiple commands produce

If your app is generating the error related to the multiple .app files then removing the .plist files from "Copy bundle Resources" WILL NOT WORK.

If the error is related to .app file then follow the following steps

  1. Select the Target.

  2. Go to Build Phases tab.

  3. Remove the items listed in Output Files
  4. Compile the code if it compiles successfully then not follow the next steps.
  5. If code does not compile successfully and Xcode may give you an error related to "Library not found". Then add the missing library in General Tab in Linked Frameworks and Libraries that Xcode mentioned in the error.
  6. Keep adding these libraries (that Xcode ask through compile errors) in Linked Frameworks and Libraries until the code compiles successfully.

    Hope this helps.

Adding header to all request with Retrofit 2

For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1

 public OkHttpClient getHeader(final String authorizationValue ) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addNetworkInterceptor(
                        new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {
                                Request request = null;
                                if (authorizationValue != null) {
                                    Log.d("--Authorization-- ", authorizationValue);

                                    Request original = chain.request();
                                    // Request customization: add request headers
                                    Request.Builder requestBuilder = original.newBuilder()
                                            .addHeader("Authorization", authorizationValue);

                                    request = requestBuilder.build();
                                }
                                return chain.proceed(request);
                            }
                        })
                .build();
        return okClient;

    }

Now in your retrofit object add this header in the client

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getHeader(authorizationValue))
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Converting Pandas dataframe into Spark dataframe error

In spark version >= 3 you can convert pandas dataframes to pyspark dataframe in one line

use spark.createDataFrame(pandasDF)

dataset = pd.read_csv("data/AS/test_v2.csv")

sparkDf = spark.createDataFrame(dataset);

if you are confused about spark session variable, spark session is as follows

sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]"))

spark = SparkSession \
    .builder \
    .getOrCreate()

How to paste yanked text into the Vim command line

For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.

PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.

How can I fix MySQL error #1064?

TL;DR

Error #1064 means that MySQL can't understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this "syntax" of which you speak? Is it witchcraft?

      Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you'll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.

      I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.

    I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

Change date format in a Java string

[edited to include BalusC's corrections] The SimpleDateFormat class should do the trick:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

WCF, Service attribute value in the ServiceHost directive could not be found

I got this error when trying to add the Service reference for the first Silverlight enabled WCF in the same solution. I just build the .Web project and it started working..

Exception: "URI formats are not supported"

Try This

ImagePath = "http://localhost/profilepics/abc.png";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();

I need an unordered list without any bullets

 <div class="custom-control custom-checkbox left">
    <ul class="list-unstyled">
        <li>
         <label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
         </label>
        </li>
     </ul>
</div>

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

This IP, site or mobile application is not authorized to use this API key

For iOS or Android apps, the key needs an extra privilege granted.

Go to the Google Console -> APIs and Services -> Library. Tap the Places library for your platform and then tap Enable.

See https://developers.google.com/maps/gmp-get-started#enable-api-sdk

How to iterate over the keys and values with ng-repeat in AngularJS?

Here's a working example:

<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
  <b>{{key}}</b> : {{value}}
</div>

edited

PHP function use variable from outside

I suppose this depends on your architecture and whatever else you may need to consider, but you could also take the object-oriented approach and use a class.

class ClassName {

    private $site_url;

    function __construct( $url ) {
        $this->site_url = $url;
    }

    public function parts( string $part ) {
        echo 'http://' . $this->site_url . 'content/' . $part . '.php';
    }

    # You could build a bunch of other things here
    # too and still have access to $this->site_url.
}

Then you can create and use the object wherever you'd like.

$obj = new ClassName($site_url);
$obj->parts('part_argument');

This could be overkill for what OP was specifically trying to achieve, but it's at least an option I wanted to put on the table for newcomers since nobody mentioned it yet.

The advantage here is scalability and containment. For example, if you find yourself needing to pass the same variables as references to multiple functions for the sake of a common task, that could be an indicator that a class is in order.

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

Convert float64 column to int64 in Pandas

Solution for pandas 0.24+ for converting numeric with missing values:

df = pd.DataFrame({'column name':[7500000.0,7500000.0, np.nan]})
print (df['column name'])
0    7500000.0
1    7500000.0
2          NaN
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)

ValueError: Cannot convert non-finite values (NA or inf) to integer

#http://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html
df['column name'] = df['column name'].astype('Int64')
print (df['column name'])
0    7500000
1    7500000
2        NaN
Name: column name, dtype: Int64

I think you need cast to numpy.int64:

df['column name'].astype(np.int64)

Sample:

df = pd.DataFrame({'column name':[7500000.0,7500000.0]})
print (df['column name'])
0    7500000.0
1    7500000.0
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)
#same as
#df['column name'] = df['column name'].astype(pd.np.int64)
print (df['column name'])
0    7500000
1    7500000
Name: column name, dtype: int64

If some NaNs in columns need replace them to some int (e.g. 0) by fillna, because type of NaN is float:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].fillna(0).astype(np.int64)
print (df['column name'])
0    7500000
1          0
Name: column name, dtype: int64

Also check documentation - missing data casting rules

EDIT:

Convert values with NaNs is buggy:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].values.astype(np.int64)
print (df['column name'])
0                7500000
1   -9223372036854775808
Name: column name, dtype: int64

JavaScript code for getting the selected value from a combo box

There is an unnecessary hashtag; change the code to this:

var e = document.getElementById("ticket_category_clone").value;

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

Get property value from C# dynamic object by string (reflection?)

you can try like this:

d?.property1 , d?.property2

I have tested it and working with .netcore 2.1

How to tell which row number is clicked in a table?

$('tr').click(function(){
 alert( $('tr').index(this) );
});

For first tr, it alerts 0. If you want to alert 1, you can add 1 to index.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

Why is list initialization (using curly braces) better than the alternatives?

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

git: fatal: I don't handle protocol '??http'

If you are using Git Extensions GUI or GitHub Desktop (means if you're using any UI software and not command-line tool) to clone the repo then you have to copy and paste only the URL i.e. https://... So there is no need to have git clone before URL as That Software will do it itself.

How to select rows that have current day's timestamp?

SELECT * FROM `table` WHERE timestamp >= CURDATE()

it is shorter , there is no need to use 'AND timestamp < CURDATE() + INTERVAL 1 DAY'

because CURDATE() always return current day

MySQL CURDATE() Function

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

Turn off iPhone/Safari input element rounding

The accepted answer made radio button disappear on Chrome. This works:

input:not([type="radio"]):not([type="checkbox"]) {
    -webkit-appearance: none;
    border-radius: 0;
}

How do I access my SSH public key?

On terminal cat ~/.ssh/id_rsa.pub

explanation

  1. cat is a standard Unix utility that reads files and prints output
  2. ~ Is your Home User path
  3. /.ssh - your hidden directory contains all your ssh certificates
  4. id_rsa.pub OR id_dsa.pub are RSA public keys, (the private key located on the client machine). the primary key for example can be used to enable cloning project from remote repository securely to your client end point.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How to load GIF image in Swift?

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)

    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as! Double

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    for i in 0..<count {
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}

Here is the file updated for Swift 3

How to access Winform textbox control from another class?

Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.

python exception message capturing

Use str(ex) to print execption

try:
   #your code
except ex:
   print(str(ex))

Get attribute name value of <input>

While there is no denying that jQuery is a powerful tool, it is a really bad idea to use it for such a trivial operation as "get an element's attribute value".

Judging by the current accepted answer, I am going to assume that you were able to add an ID attribute to your element and use that to select it.

With that in mind, here are two pieces of code. First, the code given to you in the Accepted Answer:

$("#ID").attr("name");

And second, the Vanilla JS version of it:

document.getElementById('ID').getAttribute("name");

My results:

  • jQuery: 300k operations / second
  • JavaScript: 11,000k operations / second

You can test for yourself here. The "plain JavaScript" vesion is over 35 times faster than the jQuery version.

Now, that's just for one operation, over time you will have more and more stuff going on in your code. Perhaps for something particularly advanced, the optimal "pure JavaScript" solution would take one second to run. The jQuery version might take 30 seconds to a whole minute! That's huge! People aren't going to sit around for that. Even the browser will get bored and offer you the option to kill the webpage for taking too long!

As I said, jQuery is a powerful tool, but it should not be considered the answer to everything.

How to add an image to the emulator gallery in android studio?

After trying to add an image via the Device Monitor or via drop, I could find it when exploring, but it was still not shown in the Gallery.

For me, it helped to eject the (virtual) sdcard from Settings > Storage & USB and reinserting it.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

How to while loop until the end of a file in Python without checking for empty line?

Don't loop through a file this way. Instead use a for loop.

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

In fact your whole program is just:

VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

That said, if you really want to keep using a while loop for some misguided reason:

while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

I found that (at least in Visual Studio 2010) you need to set the output verbosity to at least Detailed to be able to spot the problem.

It might be that my problem was a reference that was previously a GAC reference, but that was no longer the case after my machine's reinstall.

Get key from a HashMap using the value

We can get KEY from VALUE. Below is a sample code_

 public class Main {
  public static void main(String[] args) {
    Map map = new HashMap();
    map.put("key_1","one");
    map.put("key_2","two");
    map.put("key_3","three");
    map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four")); } public static Object getKeyFromValue(Map hm, Object value) { for (Object o : hm.keySet()) { if (hm.get(o).equals(value)) { return o; } } return null; } }

I hope this will help everyone.

How to create an Excel File with Nodejs?

Use msexcel-builder. Install it with:

npm install msexcel-builder

Then:

// Create a new workbook file in current working-path 
var workbook = excelbuilder.createWorkbook('./', 'sample.xlsx')

// Create a new worksheet with 10 columns and 12 rows 
var sheet1 = workbook.createSheet('sheet1', 10, 12);

// Fill some data 
sheet1.set(1, 1, 'I am title');
for (var i = 2; i < 5; i++)
  sheet1.set(i, 1, 'test'+i);

// Save it 
workbook.save(function(ok){
  if (!ok) 
    workbook.cancel();
  else
    console.log('congratulations, your workbook created');
});

Is it good practice to make the constructor throw an exception?

This is totally valid, I do it all the time. I usually use IllegalArguemntException if it is a result of parameter checking.

In this case I wouldn't suggest asserts because they are turned off in a deployment build and you always want to stop this from happening, but they are valid if your group does ALL it's testing with asserts turned on and you think the chance of missing a parameter problem at runtime is more acceptable than throwing an exception that is maybe more likely to cause a runtime crash.

Also, an assert would be more difficult for the caller to trap, this is easy.

You probably want to list it as a "throws" in your method's javadocs along with the reason so that callers aren't surprised.

Array versus linked-list

The difference between an array and a linked list is that an array is an index based data structure, every element is associated with an index whereas the linked list is a data structure that uses references, each node is referred to another node. In array size is fixed whereas in link list size is not fixed.

How do I get the classes of all columns in a data frame?

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

Padding characters in printf

Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.

function create-console-spanner() {
    # 1: left-side-text, 2: right-side-text
    local spanner="";
    eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
    printf "%s %s %s" "$1" "$spanner" "$2";
}

Example: create-console-spanner "loading graphics module" "[success]"

Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.

# Author: Triston J. Taylor <[email protected]>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite

declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);

declare -i PAINT_ACTIVE=1;

function paint-replace() {
    local contents=$(cat)
    echo "${contents//$1/$2}"
}

source <(cat <<EOF
function paint-activate() {
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)

source <(cat <<EOF
function paint-deactivate(){
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;    
}
EOF
)

function paint-get-spanner() {
    (( $# == 0 )) && set -- - 0;
    declare -i l=$(( `tput cols` - ${2}))
    eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}

function paint-span() {
    local left_format=$1 right_format=$3
    local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
    paint-format "$left_format";
    paint-get-spanner "$2" $(( left_length + right_length));
    paint-format "$right_format";
}

function paint-format() {
    local VAR="" OPTIONS='';
    local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
    while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
        if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
        if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
    done;
    OPTIONS+=" --"
    local format="$1"; shift;
    if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
        format=$(paint-activate "$format&none;")
    else
        format=$(paint-deactivate "$format")
    fi
    printf $OPTIONS "${format}" "$@";
    (( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}

function paint-show-pallette() {
    local -i PAINT_ACTIVE=1
    paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
    paint-format "  Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}

To print a color, that's simple enough: paint-format "&red;This is %s\n" red And you might want to get bold later on: paint-format "&bold;%s!\n" WOW

The -l option to the paint-format function measures the text so you can do console font metrics operations.

The -v option to the paint-format function works the same as printf but cannot be supplied with -l

Now for the spanning!

paint-span "hello " . " &blue;world" [note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]

and the output of that is:

hello ............................. world

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

I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii.

Here is what I will do:

In [53]: s='somestring'

In [54]: u=u'someunicodestring'

In [55]: d={}

In [56]: for each in s,u,d:
    if hasattr(each, 'keys'):
        print list(set(each.values()))
    elif hasattr(each, 'lower'):
        print [each]
    else:
        print "error"
   ....:         
   ....:         
['somestring']
[u'someunicodestring']
[]

The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.

must appear in the GROUP BY clause or be used in an aggregate function

For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is

SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:

 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error. If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:

  cname | wmname |        avg           
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;? Should it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.

In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

Ruby Hash to array of values

There is also this one:

hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]

Why it works:

The & calls to_proc on the object, and passes it as a block to the method.

something {|i| i.foo }
something(&:foo)

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Measure the time it takes to execute a t-sql query

even better, this will measure the average of n iterations of your query! Great for a more accurate reading.

declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100

while @i < @itrs
begin
declare @t0 datetime = GETDATE()

--your query here

declare @t1 datetime = GETDATE()

set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)

set @i = @i + 1
end

select @tTotal/@itrs

What is the purpose of a self executing function in javascript?

I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

  1. Better namespace management (Avoiding Namespace Pollution -> JS Module)
  2. Closures (Simulating Private Class Members, as known from OOP)

The first one has been explained very well. For the second one, please study following example:

var MyClosureObject = (function (){
  var MyName = 'Michael Jackson RIP';
  return {
    getMyName: function () { return MyName;},
    setMyName: function (name) { MyName = name}
  }
}());

Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

Let us try some experiments:

I can get MyName using getMyName and it works:

 console.log(MyClosureObject.getMyName()); 
 // Michael Jackson RIP

The following ingenuous approach would not work:

console.log(MyClosureObject.MyName); 
// undefined

But I can set an another name and get the expected result:

MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName()); 
// George Michael RIP

Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.

HTTP Error 503, the service is unavailable

i see this error after install url rewrite module i try to install previous version of it from: https://www.microsoft.com/en-us/download/details.aspx?id=7435 it fixed my error

How to fix missing dependency warning when using useEffect React Hook?

These warnings are very helpful for finding components that do not update consistently: https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies.

However, If you want to remove the warnings throughout your project, you can add this to your eslint config:

  {
  "plugins": ["react-hooks"],
  "rules": {
    "react-hooks/exhaustive-deps": 0
    }
  }

How to get Chrome to allow mixed content?

On OSX the following works from the command line:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content

Find an object in array?

Swift 3

If you need the object use:

array.first{$0.name == "Foo"}

(If you have more than one object named "Foo" then first will return the first object from an unspecified ordering)

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

Query to get all rows from previous month

Alternative with single condition

SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
    = YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1

set div height using jquery (stretch div height)

I think will work.

$('#DivID').height('675px');

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

For any of those who are experiencing this on Windows and none of the above worked, try running this from cmd.exe. Executing these commands via PowerShell caused the install to fail each time.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

This should not happen. Can you try doing this? Use the system properties and set the property as below:

Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "10.101.3.229");

And if you have a port associated, then set this as well.

properties.setProperty("mail.smtp.port", "8080");

plain count up timer in javascript

Here is one using .padStart():

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8' />
  <title>timer</title>
</head>
<body>
  <span id="minutes">00</span>:<span id="seconds">00</span>

  <script>
    const minutes = document.querySelector("#minutes")
    const seconds = document.querySelector("#seconds")
    let count = 0;

    const renderTimer = () => {
      count += 1;
      minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
      seconds.innerHTML = (count % 60).toString().padStart(2, "0");
    }

    const timer = setInterval(renderTimer, 1000)
  </script>
</body>
</html>

From MDN:

The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.

Android Design Support Library expandable Floating Action Button(FAB) menu

Another option for the same result with ConstraintSet animation:

fab animation example

1) Put all the animated views in one ConstraintLayout

2) Animate it from code like this (if you want some more effects its up to you..this is only example)

menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state

I put animation code in extension file but its not necessary.

fun FloatingActionButton.expandMenu(
    menuItem1: View,
    menuItem2: View,
    descriptionItem1: TextView,
    descriptionItem2: TextView,
    parentConstraintLayout: ConstraintLayout,
    isMenuOpened: (Boolean)-> Unit
) {
    val constraintSet = ConstraintSet()
    constraintSet.clone(parentConstraintLayout)

    constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
    constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
    constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    val transition = AutoTransition()
    transition.duration = 150
    transition.interpolator = AccelerateInterpolator()

    transition.addListener(object: Transition.TransitionListener {
        override fun onTransitionEnd(p0: Transition) {
            isMenuOpened(true)
        }
        override fun onTransitionResume(p0: Transition) {}
        override fun onTransitionPause(p0: Transition) {}
        override fun onTransitionCancel(p0: Transition) {}
        override fun onTransitionStart(p0: Transition) {}
    })

    TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
    constraintSet.applyTo(parentConstraintLayout)
}

How to prevent Browser cache for php site

Here, if you want to control it through HTML: do like below Option 1:

<meta http-equiv="expires" content="Sun, 01 Jan 2014 00:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache" />

And if you want to control it through PHP: do it like below Option 2:

header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');

AND Option 2 IS ALWAYS BETTER in order to avoid proxy based caching issue.

How to bring a window to the front?

Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.

Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).

That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:

if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();

(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).

While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.

I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.

2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront method do this (in conjunction with modified code from what is above):

setVisible(true);
toFront();
requestFocus();
repaint();

...

public @Override void toFront() {
    int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;

    super.setExtendedState(sta);
    super.setAlwaysOnTop(true);
    super.toFront();
    super.requestFocus();
    super.setAlwaysOnTop(false);
}

As of Java 8_20, this code seems to be working fine.

How do I rename the extension for a bunch of files?

rename 's/\.html$/\.txt/' *.html

does exactly what you want.

Handling optional parameters in javascript

If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:

function getData(id, opt){
    var data = voodooMagic(id, opt.parameters);
    if (opt.callback!=undefined)
      opt.callback.call(data);
    return data;         
}

getData(5, {parameters: "1,2,3", callback: 
    function(){for (i=0;i<=1;i--)alert("FAIL!");}
});

How can I avoid running ActiveRecord callbacks?

I faced the same problem when I wanted to run a Rake Task but without running the callbacks for every record I was saving. This worked for me (Rails 5), and it must work for almost every version of Rails:

class MyModel < ApplicationRecord
  attr_accessor :skip_callbacks
  before_create :callback1
  before_update :callback2
  before_destroy :callback3

  private
  def callback1
    return true if @skip_callbacks
    puts "Runs callback1"
    # Your code
  end
  def callback2
    return true if @skip_callbacks
    puts "Runs callback2"
    # Your code
  end
  # Same for callback3 and so on....
end

The way it works is that it just returns true in the first line of the method it skip_callbacks is true, so it doesn't run the rest of the code in the method. To skip callbacks you just need to set skip_callbacks to true before saving, creating, destroying:

rec = MyModel.new() # Or Mymodel.find()
rec.skip_callbacks = true
rec.save