Programs & Examples On #Django models

The centerpiece of the Django object-relational mapping scheme is the Model.

What's the difference between django OneToOneField and ForeignKey?

A ForeignKey is for one-to-many, so a Car object might have many Wheels, each Wheel having a ForeignKey to the Car it belongs to. A OneToOneField would be like an Engine, where a Car object can have one and only one.

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

I am using django==1.11. The answer get the most vote is actually wrong. Checking the document from django, it says:

initial -- A value to use in this Field's initial display. This value is not used as a fallback if data isn't given.

And if you dig into the code of form validation process, you will find that, for each fields, form will call it's widget's value_from_datadict to get actual value, so this is the place where we can inject default value.

To do this for BooleanField, we can inherit from CheckboxInput, override default value_from_datadict and init function.

class CheckboxInput(forms.CheckboxInput):
    def __init__(self, default=False, *args, **kwargs):
        super(CheckboxInput, self).__init__(*args, **kwargs)
        self.default = default

    def value_from_datadict(self, data, files, name):
        if name not in data:
            return self.default
        return super(CheckboxInput, self).value_from_datadict(data, files, name)

Then use this widget when creating BooleanField.

class ExampleForm(forms.Form):
    bool_field = forms.BooleanField(widget=CheckboxInput(default=True), required=False)

How do I do a not equal in Django queryset filtering?

the field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range

date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second

isnull
regex
iregex

I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you'll get exactly what you need for just about any possible query.

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

If you do not find interest in overriding save method, you can do

  model_fields = [f.name for f in YourModel._meta.get_fields()]
  valid_data = {
        key: new_data[key]
        for key in model_fields
        if key in new_data.keys()
  }

  for (key, value) in valid_data.items():
        if getattr(instance, key) != value:
           print ('Data has changed')

        setattr(instance, key, value)

 instance.save()

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.

After that you can just easily get the wanted prop:

for employee in employees:
    print(employee.eng_name)

Or in the template:

{% for employee in employees %}

    <p>{{ employee.eng_name }}</p>

{% endfor %}

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

Django error - matching query does not exist

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return Comment.objects.get(pk=id)
    except Comment.DoesNotExist:
        return False

Getting a count of objects in a queryset in django

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

How to limit the maximum value of a numeric field in a Django model?

Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:

#Imports
from django.core.exceptions import ValidationError      

class validate_range_or_null(object):
    compare = lambda self, a, b, c: a > c or a < b
    clean = lambda self, x: x
    message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
    code = 'limit_value'

    def __init__(self, limit_min, limit_max):
        self.limit_min = limit_min
        self.limit_max = limit_max

    def __call__(self, value):
        cleaned = self.clean(value)
        params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
        if value:  # make it optional, remove it to make required, or make required on the model
            if self.compare(cleaned, self.limit_min, self.limit_max):
                raise ValidationError(self.message, code=self.code, params=params)

And it can be used as such:

class YourModel(models.Model):

    ....
    no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])

The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.

Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.

Hope this helps :) More on Validators in Django.

PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.

How to query as GROUP BY in django?

An easy solution, but not the proper way is to use raw SQL:

results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')

Another solution is to use the group_by property:

query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)

You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

How to delete a record in Django models?

you can delete the objects directly from the admin panel or else there is also an option to delete specific or selected id from an interactive shell by typing in python3 manage.py shell (python3 in Linux). If you want the user to delete the objects through the browser (with provided visual interface) e.g. of an employee whose ID is 6 from the database, we can achieve this with the following code, emp = employee.objects.get(id=6).delete()

THIS WILL DELETE THE EMPLOYEE WITH THE ID is 6.

If you wish to delete the all of the employees exist in the DB instead of get(), specify all() as follows: employee.objects.all().delete()

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

Create Django model or update if exists

This should be the answer you are looking for

EmployeeInfo.objects.update_or_create(
    #id or any primary key:value to search for
    identifier=your_id, 
    #if found update with the following or save/create if not found
    defaults={'name':'your_name'}
)

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

How do I filter query objects by date range in Django?

you can use "__range" for example :

from datetime import datetime
start_date=datetime(2009, 12, 30)
end_end=datetime(2020,12,30)
Sample.objects.filter(date__range=[start_date,end_date])

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

Django: Get list of model fields?

In sometimes we need the db columns as well:

def get_db_field_names(instance):
   your_fields = instance._meta.local_fields
   db_field_names=[f.name+'_id' if f.related_model is not None else f.name  for f in your_fields]
   model_field_names = [f.name for f in your_fields]
   return db_field_names,model_field_names

Call the method to get the fields:

db_field_names,model_field_names=get_db_field_names(Mymodel)

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

If you have a lot of relation attribute fields to use in list_display and do not want create a function (and it's attributes) for each one, a dirt but simple solution would be override the ModelAdmin instace __getattr__ method, creating the callables on the fly:

class DynamicLookupMixin(object):
    '''
    a mixin to add dynamic callable attributes like 'book__author' which
    return a function that return the instance.book.author value
    '''

    def __getattr__(self, attr):
        if ('__' in attr
            and not attr.startswith('_')
            and not attr.endswith('_boolean')
            and not attr.endswith('_short_description')):

            def dyn_lookup(instance):
                # traverse all __ lookups
                return reduce(lambda parent, child: getattr(parent, child),
                              attr.split('__'),
                              instance)

            # get admin_order_field, boolean and short_description
            dyn_lookup.admin_order_field = attr
            dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False)
            dyn_lookup.short_description = getattr(
                self, '{}_short_description'.format(attr),
                attr.replace('_', ' ').capitalize())

            return dyn_lookup

        # not dynamic lookup, default behaviour
        return self.__getattribute__(attr)


# use examples    

@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin, DynamicLookupMixin):
    list_display = ['book__author', 'book__publisher__name',
                    'book__publisher__country']

    # custom short description
    book__publisher__country_short_description = 'Publisher Country'


@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin, DynamicLookupMixin):
    list_display = ('name', 'category__is_new')

    # to show as boolean field
    category__is_new_boolean = True

As gist here

Callable especial attributes like boolean and short_description must be defined as ModelAdmin attributes, eg book__author_verbose_name = 'Author name' and category__is_new_boolean = True.

The callable admin_order_field attribute is defined automatically.

Don't forget to use the list_select_related attribute in your ModelAdmin to make Django avoid aditional queries.

How to do SELECT MAX in Django?

Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.

You can give the field name when calling that function:

max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details

Or you can already give that field name in your models meta data:

from django.db import models

class YourModel(models.Model):
    #your class definition
    class Meta:
        get_latest_by = 'rating'

Now you can call 'latest()' without any parameters:

max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

How to 'bulk update' with Django?

Consider using django-bulk-update found here on GitHub.

Install: pip install django-bulk-update

Implement: (code taken directly from projects ReadMe file)

from bulk_update.helper import bulk_update

random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()

for person in people:
    r = random.randrange(4)
    person.name = random_names[r]

bulk_update(people)  # updates all columns using the default db

Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.

What is a "slug" in Django?

The term 'slug' comes from the world of newspaper production.

It's an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'kate-and-william' story?".

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william.

Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201, although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had "slug lines" at the start of each scene, which basically sets the background for that scene (where, when, and so on). It's very similar in that it's a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the 'piece of metal' definition to the 'story summary' definition. From there, it's a short step from proper printing to the online world.


(a) "Godel Escher, Bach", by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, "Metamagical Themas".

How to filter empty or NULL names in a QuerySet?

From Django 1.8,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)

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

Edited: Fixed mistake in code that stopped it working if there were no YourModel entries in the db.

There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.

However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).

In your models.py

from django.db import models

def from_500():
    '''
    Returns the next default value for the `ones` field,
    starts from 500
    '''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `ones` field and get the largest entry
    largest = YourModel.objects.all().order_by('ones').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 500
        return 500
    # If an instance of `YourModel` is returned, we get it's
    # `ones` attribute and increment it by 1
    return largest.ones + 1

def add_ten():
    ''' Returns the next default value for the `tens` field'''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `tens` field and get the largest entry
    largest = YourModel.objects.all().order_by('tens').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 10
        return 10
    # If an instance of `YourModel` is returned, we get it's
    # `tens` attribute and increment it by 10
    return largest.tens + 10


class YourModel(model.Model):
    ones = models.IntegerField(primary_key=True,
                               default=from_500)
    tens = models.IntegerField(default=add_ten)

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

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

If the key field is nullable, then you can also set the value to null before attempting to delete it:

cursor.execute("UPDATE myapp_item SET myapp_style_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed() 

cursor.execute("UPDATE myapp_style SET myapp_item_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed()

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()

What is the most efficient way to store a list in the Django models?

Remember that this eventually has to end up in a relational database. So using relations really is the common way to solve this problem. If you absolutely insist on storing a list in the object itself, you could make it for example comma-separated, and store it in a string, and then provide accessor functions that split the string into a list. With that, you will be limited to a maximum number of strings, and you will lose efficient queries.

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

What is the difference between null=True and blank=True in Django?

You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.

I follow this table, from Two Scoops of Django: enter image description here

Table showing when to use null or blank for each field type

Django: Display Choice Value

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

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

(did not mean to make the comment)

Ok, it doesn't really depend on types in that way. I may have mis-understood the original question here so forgive me if that is the case. If you create serliazers.py then in there you create classes that have meta classes.

Class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = modelName
        fields =('csv','of','fields')

Then when you get the data in the view class you can:

model_data - Model.objects.filter(...)
serializer = MyModelSerializer(model_data, many=True)
return Response({'data': serilaizer.data}, status=status.HTTP_200_OK)

That is pretty much what I have in a vareity of places and it returns nice JSON via the JSONRenderer.

As I said this is courtesy of the DjangoRestFramework so it's worth looking into that.

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

how to import csv data into django models

If you're working with new versions of Django (>10) and don't want to spend time writing the model definition. you can use the ogrinspect tool.

This will create a code definition for the model .

python manage.py ogrinspect [/path/to/thecsv] Product

The output will be the class (model) definition. In this case the model will be called Product. You need to copy this code into your models.py file.

Afterwards you need to migrate (in the shell) the new Product table with:

python manage.py makemigrations
python manage.py migrate

More information here: https://docs.djangoproject.com/en/1.11/ref/contrib/gis/tutorial/

Do note that the example has been done for ESRI Shapefiles but it works pretty good with standard CSV files as well.

For ingesting your data (in CSV format) you can use pandas.

import pandas as pd
your_dataframe = pd.read_csv(path_to_csv)
# Make a row iterator (this will go row by row)
iter_data = your_dataframe.iterrows()

Now, every row needs to be transformed into a dictionary and use this dict for instantiating your model (in this case, Product())

# python 2.x
map(lambda (i,data) : Product.objects.create(**dict(data)),iter_data

Done, check your database now.

Programmatically saving image to Django ImageField

What I did was to create my own storage that will just not save the file to the disk:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I've used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

Django auto_now and auto_now_add

Any field with the auto_now attribute set will also inherit editable=False and therefore will not show up in the admin panel. There has been talk in the past about making the auto_now and auto_now_add arguments go away, and although they still exist, I feel you're better off just using a custom save() method.

So, to make this work properly, I would recommend not using auto_now or auto_now_add and instead define your own save() method to make sure that created is only updated if id is not set (such as when the item is first created), and have it update modified every time the item is saved.

I have done the exact same thing with other projects I have written using Django, and so your save() would look like this:

from django.utils import timezone

class User(models.Model):
    created     = models.DateTimeField(editable=False)
    modified    = models.DateTimeField()

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.created = timezone.now()
        self.modified = timezone.now()
        return super(User, self).save(*args, **kwargs)

Hope this helps!

Edit in response to comments:

The reason why I just stick with overloading save() vs. relying on these field arguments is two-fold:

  1. The aforementioned ups and downs with their reliability. These arguments are heavily reliant on the way each type of database that Django knows how to interact with treats a date/time stamp field, and seems to break and/or change between every release. (Which I believe is the impetus behind the call to have them removed altogether).
  2. The fact that they only work on DateField, DateTimeField, and TimeField, and by using this technique you are able to automatically populate any field type every time an item is saved.
  3. Use django.utils.timezone.now() vs. datetime.datetime.now(), because it will return a TZ-aware or naive datetime.datetime object depending on settings.USE_TZ.

To address why the OP saw the error, I don't know exactly, but it looks like created isn't even being populated at all, despite having auto_now_add=True. To me it stands out as a bug, and underscores item #1 in my little list above: auto_now and auto_now_add are flaky at best.

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

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

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

What does on_delete do on Django models?

CASCADE will also delete the corresponding field connected with it.

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

The Django documentation for database queries includes a section on copying model instances. Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to None, and save the object again:

blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1

blog.pk = None
blog.save() # blog.pk == 2

In this snippet, the first save() creates the original object, and the second save() creates the copy.

If you keep reading the documentation, there are also examples on how to handle two more complex cases: (1) copying an object which is an instance of a model subclass, and (2) also copying related objects, including objects in many-to-many relations.


Note on miah's answer: Setting the pk to None is mentioned in miah's answer, although it's not presented front and center. So my answer mainly serves to emphasize that method as the Django-recommended way to do it.

Historical note: This wasn't explained in the Django docs until version 1.4. It has been possible since before 1.4, though.

Possible future functionality: The aforementioned docs change was made in this ticket. On the ticket's comment thread, there was also some discussion on adding a built-in copy function for model classes, but as far as I know they decided not to tackle that problem yet. So this "manual" way of copying will probably have to do for now.

How to create Password Field in Model Django

See my code which may help you. models.py

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=100)
    instrument_purchase = models.CharField(max_length=100)
    house_no = models.CharField(max_length=100)
    address_line1 = models.CharField(max_length=100)
    address_line2 = models.CharField(max_length=100)
    telephone = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=20)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)

    def __str__(self):
        return self.name

forms.py

from django import forms
from models import *

class CustomerForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = Customer
        fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')

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

You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

import calendar
tuple((m, m) for m in calendar.month_name[1:])

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 DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

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)

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

'NOT NULL constraint failed' after adding to models.py

You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True and create and run migration.

django - get() returned more than one topic

To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

def updateUserCollection(request):
    data = json.loads(request.body)
    card_id = data['card_id']
    action = data['action']

    user = request.user
    card = Cards.objects.get(card_id=card_id)

    if data-action == 'add':
        collection = Collection.objects.get_or_create(user=user, card=card)
        collection.quantity + 1
        collection.save()

    elif data-action == 'remove':
        collection = Cards.objects.filter(user=user, card=card)
        collection.quantity = 0
        collection.update()

Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

Django database query: How to get object by id?

You can use:

objects_all=Class.objects.filter(filter_condition="")

This will return a query set even if it gets one object. If you need exactly one object use:

obj=Class.objects.get(conditon="")

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

You can change the property categorie of the class Article like this:

categorie = models.ForeignKey(
    'Categorie',
    on_delete=models.CASCADE,
)

and the error should disappear.

Eventually you might need another option for on_delete, check the documentation for more details:

https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey

EDIT:

As you stated in your comment, that you don't have any special requirements for on_delete, you could use the option DO_NOTHING:

# ...
on_delete=models.DO_NOTHING,
# ...

How do I create a slug in Django?

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(Test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(Test, self).save(*args, **kwargs)

Bulk create model objects in django

as of the django development, there exists bulk_create as an object manager method which takes as input an array of objects created using the class constructor. check out django docs

matching query does not exist Error in Django

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

Setting the selected value on a Django forms.ChoiceField

Try setting the initial value when you instantiate the form:

form = MyForm(initial={'max_number': '3'})

How to update fields in a model without creating a new record in django?

Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.

Also get-set attribute-save may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.

In such cases query expressions together with update may by useful:

TemperatureData.objects.filter(id=1).update(value=F('value') + 1)

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

Get model's fields in Django

Another way is add functions to the model and when you want to override the date you can call the function.

class MyModel(models.Model):
    name = models.CharField(max_length=256)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def set_created_date(self, created_date):
        field = self._meta.get_field('created')
        field.auto_now_add = False
        self.created = created_date

    def set_modified_date(self, modified_date):
        field = self._meta.get_field('modified')
        field.auto_now = False
        self.modified = modified_date

my_model = MyModel(name='test')
my_model.set_modified_date(new_date)
my_model.set_created_date(new_date)
my_model.save()

How to select a record and update it, with a single queryset in Django?

Use the queryset object update method:

MyModel.objects.filter(pk=some_value).update(field1='some value')

How do you serialize a model instance in Django?

To avoid the array wrapper, remove it before you return the response:

import json
from django.core import serializers

def getObject(request, id):
    obj = MyModel.objects.get(pk=id)
    data = serializers.serialize('json', [obj,])
    struct = json.loads(data)
    data = json.dumps(struct[0])
    return HttpResponse(data, mimetype='application/json')

I found this interesting post on the subject too:

http://timsaylor.com/convert-django-model-instances-to-dictionaries

It uses django.forms.models.model_to_dict, which looks like the perfect tool for the job.

Fastest way to get the first object from a queryset in django?

You should use django methods, like exists. Its there for you to use it.

if qs.exists():
    return qs[0]
return None

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

How do I get the current date and current time only respectively in Django?

import datetime

datetime.date.today()  # Returns 2018-01-15

datetime.datetime.now() # Returns 2018-01-15 09:00

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

How can I add JAR files to the web-inf/lib folder in Eclipse?

Found a solution. This problem happens, when you import a project.

The solution is simple

  1. Right click -> Properties
  2. Project Facets -> Check Dyanmic Web Module and Java Version
  3. Apply Setting.

Now you should see the web app libraries showing your jars added.

Python Decimals format

If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

How to make image hover in css?

You've got an a tag containing an img tag. That's your normal state. You then add a background-image as your hover state, and it's appearing in the background of your a tag - behind the img tag.

You should probably create a CSS sprite and use background positions, but this should get you started:

<div>
    <a href="home.html"></a>
</div>

div a {
    width:  59px;
    height: 59px;
    display: block;
    background-image: url('images/btnhome.png');
}

div a:hover {
    background-image: url('images/btnhomeh.png);
}

This A List Apart Article from 2004 is still relevant, and will give you some background about sprites, and why it's a good idea to use them instead of two different images. It's a lot better written than anything I could explain to you.

set default schema for a sql query

Very old question, but since google led me here I'll add a solution that I found useful:

Step 1. Create a user for each schema you need to be able to use. E.g. "user_myschema"

Step 2. Use EXECUTE AS to execute the SQL statements as the required schema user.

Step 3. Use REVERT to switch back to the original user.

Example: Let's say you have a table "mytable" present in schema "otherschema", which is not your default schema. Running "SELECT * FROM mytable" won't work.

Create a user named "user_otherschema" and set that user's default schema to be "otherschema".

Now you can run this script to interact with the table:

EXECUTE AS USER = 'user_otherschema';
SELECT * FROM mytable
REVERT

The revert statements resets current user, so you are yourself again.

Link to EXECUTE AS documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/execute-as-transact-sql?view=sql-server-2017

How to Join to first row

,Another aproach using common table expression:

with firstOnly as (
    select Orders.OrderNumber, LineItems.Quantity, LineItems.Description, ROW_NUMBER() over (partiton by Orders.OrderID order by Orders.OrderID) lp
    FROM Orders
        join LineItems on Orders.OrderID = LineItems.OrderID
) select *
  from firstOnly
  where lp = 1

or, in the end maybe you would like to show all rows joined?

comma separated version here:

  select *
  from Orders o
    cross apply (
        select CAST((select l.Description + ','
        from LineItems l
        where l.OrderID = s.OrderID
        for xml path('')) as nvarchar(max)) l
    ) lines

Is JavaScript a pass-by-reference or pass-by-value language?

Consider the following:

  1. Variables are pointers to values in memory.
  2. Reassigning a variable merely points that pointer at a new value.
  3. Reassigning a variable will never affect other variables that were pointing at that same object

So, forget about "pass by reference/value" don't get hung up on "pass by reference/value" because:

  1. The terms are only used to describe the behavior of a language, not necessarily the actual underlying implementation. As a result of this abstraction, critical details that are essential for a decent explanation are lost, which inevitably leads to the current situation where a single term doesn't adequately describe the actual behavior and supplementary info has to be provided
  2. These concepts were not originally defined with the intent of describing javascript in particular and so I don't feel compelled to use them when they only add to the confusion.

To answer your question: pointers are passed.


// code
var obj = {
    name: 'Fred',
    num: 1
};

// illustration
               'Fred'
              /
             /
(obj) ---- {}
             \
              \
               1


// code
obj.name = 'George';


// illustration
                 'Fred'


(obj) ---- {} ----- 'George'
             \
              \
               1


// code
obj = {};

// illustration
                 'Fred'


(obj)      {} ----- 'George'
  |          \
  |           \
 { }            1


// code
var obj = {
    text: 'Hello world!'
};

/* function parameters get their own pointer to 
 * the arguments that are passed in, just like any other variable */
someFunc(obj);


// illustration
(caller scope)        (someFunc scope)
           \             /
            \           /
             \         /
              \       /
               \     /
                 { }
                  |
                  |
                  |
            'Hello world'

Some final comments:

  • It's tempting to think that primitives are enforced by special rules while objects are not, but primitives are simply the end of the pointer chain.
  • As a final example, consider why a common attempt to clear an array doesn't work as expected.


var a = [1,2];
var b = a;

a = [];
console.log(b); // [1,2]
// doesn't work because `b` is still pointing at the original array

Locate the nginx.conf file my nginx is actually using

Running nginx -t through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).

Django check for any exists for a query

this worked for me!

if some_queryset.objects.all().exists(): print("this table is not empty")

How to align form at the center of the page in html/css

I would just use table and not the form. Its done by using margin.

table {
  margin: 0 auto;
}

also try using something like

table td {
    padding-bottom: 5px;
}

instead of <br />

and also your input should end with /> e.g:

<input type="password" name="cpwd" />

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

Such things are best answered by looking at the official specification:

  1. go to the specification: https://www.w3.org/TR/html5/

  2. search for "a element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element

  3. check "Content attributes", which lists all allowed attributes for the a element:

    • Global attributes
    • href
    • target
    • download
    • rel
    • hreflang
    • type
  4. check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes

As you will see, the alt attribute is not allowed on the a element.
Also you’d notice that the src attribute isn’t allowed either.

By validating your HTML, errors like these are reported to you.


Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a element can have another attribute in HTML 5.1: rev.

You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList();

    List<Address> allAddresses = GetAllAddresses();
    List<Employee> employees = GetAllEmployees(); // count > 1000

    List<Address> addresses = new List<Address>();

    for (int i = 0; i < employees.Count; i += 1000)
    {
        int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000;
        var query = (from address in allAddresses
                     where employees.GetRange(i, count).Contains(address.EmployeeId)
                     && address.State == "UT"
                     select address).ToList();

        addresses.AddRange(query);
    }

Hope this helps someone.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

Comments in Markdown

The following works very well

<empty line>
[whatever comment text]::

that method takes advantage of syntax to create links via reference
since link reference created with [1]: http://example.org will not be rendered, likewise any of the following will not be rendered as well

<empty line>
[whatever]::
[whatever]:whatever
[whatever]: :
[whatever]: whatever

JavaScript property access: dot notation vs. brackets?

Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

how to run python files in windows command prompt?

First set path of python https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows

and run python file

python filename.py

command line argument with python

python filename.py command-line argument

Is an HTTPS query string secure?

You can send password as MD5 hash param with some salt added. Compare it on the server side for auth.

What is the equivalent of Java's System.out.println() in Javascript?

You can always simply add an alert() prompt anywhere in a function. Especially useful for knowing if a function was called, if a function completed or where a function fails.

alert('start of function x');
alert('end of function y');
alert('about to call function a');
alert('returned from function b');

You get the idea.

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Flurry Support for iPhone 5 (ARMv7s) As I mentioned in yesterday’s post, Flurry started working on a version of the iOS SDK to support the ARMv7s processor in the new iPhone 5 immediately after the announcement on Wednesday.

I am happy to tell you that the work is done and the SDK is now available on the site.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

127 Return code from $?

If you're trying to run a program using a scripting language, you may need to include the full path of the scripting language and the file to execute. For example:

exec('/usr/local/bin/node /usr/local/lib/node_modules/uglifycss/uglifycss in.css > out.css');

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

Sending mass email using PHP

There is more into it aside from using a software. If you could create a bulk emailer program that sends intermittently. Say if you will send 5,000 recipients, create a loop that would send 38 lists per sending then pause for 10 seconds. I have an actual experience sending 500 manually per days for the past weeks and so far i have good results.

Another consideration are the content of your email. Nowadays it is a standard that you need to put your physical office address and the "unsubscribe" opt-out. These are factors that majority of recipient emails servers are checking. If you don't have these they will classify you as spammer.

Mailchimp is my best recommendation to use if you want a paid service provider in sending to your email subscriber NOT sending unsolicited or cold email marketing.

Hope it helps.

How to set HTML Auto Indent format on Sublime Text 3?

This is an adaptation of the above answer, but should be more complete.

To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.

Windows Users

Go to C:\Program Files\Sublime Text 3\Packages extract HTML.sublime-package as if it is a zip file to a directory.

Open Miscellaneous.tmPreferences and copy this contents into the file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Then re-zip the file as HTML.sublime-package and replace the existing HTML.sublime-package with the one you just created.

Close and open Sublime Text 3 and you're done!

Check whether a value exists in JSON object

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};

 var Duplicate= JSONObject .find(s => s.name== "cat");
        if (typeof (Duplicate) === "undefined") {
           alert("Not Exist");
           return;
        } else {
            if (JSON.stringify(Duplicate).length > 0) {
                alert("Value Exist");
                return;
            }
        }

Send string to stdin

Solution

You want to (1) create stdout output in one process (like echo '…') and (2) redirect that output to stdin input of another process but (3) without the use of the bash pipe mechanism. Here's a solution that matches all three conditions:

/my/bash/script < <(echo 'This string will be sent to stdin.')

The < is normal input redirection for stdin. The <(…) is bash process substitution. Roughly it creates a /dev/fd/… file with the output of the substituting command and passes that filename in place of the <(…), resulting here for example in script < /dev/fd/123. For details, see this answer.

Comparison with other solutions

  • A one-line heredoc sent to stdin script <<< 'string' only allows to send static strings, not the output of other commands.

  • Process substitution alone, such as in diff <(ls /bin) <(ls /usr/bin), does not send anything to stdin. Instead, the process output is saved into a file, and its path is passed as a command line argument. For the above example, this is equivalent to diff /dev/fd/10 /dev/fd/11, a command where diff receives no input from stdin.

Use cases

I like that, unlike the pipe mechanism, the < <(…) mechanism allows to put the command first and all input after it, as is the standard for input from command line options.

However, beyond commandline aesthetics, there are some cases where a pipe mechanism cannot be used. For example, when a certain command has to be provided as argument to another command, such as in this example with sshpass.

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

DISTINCT clause with WHERE

One simple query will do it:

SELECT * 
FROM table 
GROUP BY email 
HAVING COUNT(*) = 1;

Is there any ASCII character for <br>?

You may be looking for the special HTML character, &#10; .

You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt label.

NSUserDefaults - How to tell if a key exists

As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.

NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){

    NSLog(@"mykey found");
}

How make background image on newsletter in outlook?

The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.

The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.

<td bgcolor="#your_color" background="your_image.jpg">

<!--[if gte mso 9]>

<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>

<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>

<![endif]-->

<p>Text over background image.</p>

<!--[if gte mso 9]>

</v:shape>

<![endif]-->

</td>

source

How to add headers to OkHttp request interceptor?

Faced similar issue with other samples, this Kotlin class worked for me

import okhttp3.Interceptor
import okhttp3.Response

class CustomInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain) : Response {               
        val request = chain.request().newBuilder()
            .header("x-custom-header", "my-value")
            .build()
        return chain.proceed(request)
    }
}

Check array position for null/empty

There is no bound checking in array in C programming. If you declare array as

int arr[50];

Then you can even write as

arr[51] = 10;

The compiler would not throw an error. Hope this answers your question.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Confirm postback OnClientClick button ASP.NET

I know this is old and there are so many answers, some are really convoluted, can be quick and inline:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
                       

How to NodeJS require inside TypeScript file?

The correct syntax is:

import sampleModule = require('modulename');

or

import * as sampleModule from 'modulename';

Then compile your TypeScript with --module commonjs.

If the package doesn't come with an index.d.ts file and its package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.

How do I add a Maven dependency in Eclipse?

I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.

 Right click on project >> maven >> updateProject >> selectProject >> OK

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Remove multiple items from a Python list in just one statement

I'm reposting my answer from here because I saw it also fits in here. It allows removing multiple values or removing only duplicates of these values and returns either a new list or modifies the given list in place.


def removed(items, original_list, only_duplicates=False, inplace=False):
    """By default removes given items from original_list and returns
    a new list. Optionally only removes duplicates of `items` or modifies
    given list in place.
    """
    if not hasattr(items, '__iter__') or isinstance(items, str):
        items = [items]

    if only_duplicates:
        result = []
        for item in original_list:
            if item not in items or item not in result:
                result.append(item)
    else:
        result = [item for item in original_list if item not in items]

    if inplace:
        original_list[:] = result
    else:
        return result

Docstring extension:

"""
Examples:
---------

    >>>li1 = [1, 2, 3, 4, 4, 5, 5]
    >>>removed(4, li1)
       [1, 2, 3, 5, 5]
    >>>removed((4,5), li1)
       [1, 2, 3]
    >>>removed((4,5), li1, only_duplicates=True)
       [1, 2, 3, 4, 5]

    # remove all duplicates by passing original_list also to `items`.:
    >>>removed(li1, li1, only_duplicates=True)
      [1, 2, 3, 4, 5]

    # inplace:
    >>>removed((4,5), li1, only_duplicates=True, inplace=True)
    >>>li1
        [1, 2, 3, 4, 5]

    >>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
    >>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
    >>>li2
        ['abc', 'def', 'ghi']
"""

You should be clear about what you really want to do, modify an existing list, or make a new list with the specific items missing. It's important to make that distinction in case you have a second reference pointing to the existing list. If you have, for example...

li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the 
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]

This may or may not be the behaviour you want.

Android Studio - Failed to apply plugin [id 'com.android.application']

My problem was I had czech characters (c,ú,u,á,ó) in the project folder path.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

WunderBart's answer was the best for me. Note that you can speed it up a lot if your images are often the right way around, simply by testing the orientation first and bypassing the rest of the code if no rotation is required.

Putting all of the info from wunderbart together, something like this;

var handleTakePhoto = function () {
    let fileInput: HTMLInputElement = <HTMLInputElement>document.getElementById('photoInput');
    fileInput.addEventListener('change', (e: any) => handleInputUpdated(fileInput, e.target.files));
    fileInput.click();
}

var handleInputUpdated = function (fileInput: HTMLInputElement, fileList) {
    let file = null;

    if (fileList.length > 0 && fileList[0].type.match(/^image\//)) {
        isLoading(true);
        file = fileList[0];
        getOrientation(file, function (orientation) {
            if (orientation == 1) {
                imageBinary(URL.createObjectURL(file));
                isLoading(false);
            }
            else 
            {
                resetOrientation(URL.createObjectURL(file), orientation, function (resetBase64Image) {
                    imageBinary(resetBase64Image);
                    isLoading(false);
                });
            }
        });
    }

    fileInput.removeEventListener('change');
}


// from http://stackoverflow.com/a/32490603
export function getOrientation(file, callback) {
    var reader = new FileReader();

    reader.onload = function (event: any) {
        var view = new DataView(event.target.result);

        if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

        var length = view.byteLength,
            offset = 2;

        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;

            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    return callback(-1);
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;

                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)
                        return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        return callback(-1);
    };

    reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
};

export function resetOrientation(srcBase64, srcOrientation, callback) {
    var img = new Image();

    img.onload = function () {
        var width = img.width,
            height = img.height,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");

        // set proper canvas dimensions before transform & export
        if (4 < srcOrientation && srcOrientation < 9) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;
        }

        // transform context before drawing image
        switch (srcOrientation) {
            case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
            case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
            case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
            case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
            case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
            case 7: ctx.transform(0, -1, -1, 0, height, width); break;
            case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
            default: break;
        }

        // draw image
        ctx.drawImage(img, 0, 0);

        // export base64
        callback(canvas.toDataURL());
    };

    img.src = srcBase64;
}

How to extract a value from a string using regex and a shell?

Using ripgrep's replace option, it is possible to change the output to a capture group:

rg --only-matching --replace '$1' '(\d+) rofl'
  • --only-matching or -o outputs only the part that matches instead of the whole line.
  • --replace '$1' or -r replaces the output by the first capture group.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.

I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.

Thanks everyone!

gitx How do I get my 'Detached HEAD' commits back into master

If your detached HEAD is a fast forward of master and you just want the commits upstream, you can

git push origin HEAD:master

to push directly, or

git checkout master && git merge [ref of HEAD]

will merge it back into your local master.

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

Maven not found in Mac OSX mavericks

This solution could seem very long, but it's not. I just included many examples so that everything was clear. It worked for me in Mavericks OS.

Note: I combined and edited some of the answers shown above, added some examples and format and posted the result, so the credit goes mostly to the creators of the original posts.

  1. Download Maven from here.

  2. Open the Terminal.

  3. Extract the file you just downloaded to the location you want, either manually or by typing the following lines in the Terminal (fill the required data):

    mv [Your file name] [Destination location]/ tar -xvf [Your file name]

    For example, if our file is named "apache-maven-3.2.1-bin.tar" (Maven version 3.2.1) and we want to locate it in the "/Applications" directory, then we should type the following lines in Terminal:

    mv apache-maven-3.2.1-bin.tar /Applications/
    tar -xvf apache-maven-3.2.1-bin.tar
    
  4. If you don't have any JDK (Java Development Kit) installed on your computer, install one.

  5. Type "java -version" in Terminal. You should see something like this:

    java version "1.8.0"
    Java(TM) SE Runtime Environment (build 1.8.0-b132)
    Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
    

    Remember your java version (in the example, 1.8.0).

  6. Type "cd ~/" to go to your home folder.

  7. Type "touch .bash_profile".

  8. Type "open -e .bash_profile" to open .bash_profile in TextEdit.

  9. Type the following in TextEdit (copy everything and replace the required data):

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home export M2_HOME=[Your file location]/apache-maven-[Your Maven version]/ export PATH=$PATH:$M2_HOME/bin alias mvn='$M2_HOME/bin/mvn'

    For example, in our case we would replace "[Your Java version]" with "1.8.0" (value got in step 5), "[Your file location]" with "/Applications" (value used as "Destination Location" in step 3) and "[Your Maven version]" with "3.2.1" (Maven version observed in step 3), resulting in the following code:

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home
    export M2_HOME=/Applications/apache-maven-3.2.1/
    export PATH=$PATH:$M2_HOME/bin
    alias mvn='$M2_HOME/bin/mvn'
    
  10. Save your changes

  11. Type "source .bash_profile" to reload .bash_profile and update any functions you add.

  12. Type mvn -version. If successful you should see the following:

    Apache Maven [Your Maven version] ([Some weird stuff. Don't worry about this]) Maven home: [Your file location]/apache-maven-[Your Maven version] Java version: [You Java version], vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home/jre [Some other stuff which may vary depending on the configuration and the OS of the computer]

    In our example, the result would be the following:

    Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T18:37:52+01:00)
    Maven home: /Applications/apache-maven-3.2.1
    Java version: 1.8.0, vendor: Oracle Corporation
    Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0</b>.jdk/Contents/Home/jre
    Default locale: es_ES, platform encoding: UTF-8
    OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
    

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

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

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

Example Code :

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

Output:

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

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

Chrome: console.log, console.debug are not working

I experienced the same problem. The solution for me was to disable Firebug because Firebug was intercepting the logs in the background resulting in no logs being shown in the Chrome console.

XOR operation with two strings in java

This is the code I'm using:

private static byte[] xor(final byte[] input, final byte[] secret) {
    final byte[] output = new byte[input.length];
    if (secret.length == 0) {
        throw new IllegalArgumentException("empty security key");
    }
    int spos = 0;
    for (int pos = 0; pos < input.length; ++pos) {
        output[pos] = (byte) (input[pos] ^ secret[spos]);
        ++spos;
        if (spos >= secret.length) {
            spos = 0;
        }
    }
    return output;
}

Pipe output and capture exit status in Bash

This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.

Situation:

someprog | filter

you want the exit status from someprog and the output from filter.

Here is my solution:

((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1

echo $?

See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Dissatisfied with the other answers. The top voted answer as of 2019/3/13 is factually wrong.

The short terse version of what => means is it's a shortcut writing a function AND for binding it to the current this

const foo = a => a * 2;

Is effectively a shortcut for

const foo = function(a) { return a * 2; }.bind(this);

You can see all the things that got shortened. We didn't need function, nor return nor .bind(this) nor even braces or parentheses

A slightly longer example of an arrow function might be

const foo = (width, height) => {
  const area = width * height;
  return area;
};

Showing that if we want multiple arguments to the function we need parentheses and if we want write more than a single expression we need braces and an explicit return.

It's important to understand the .bind part and it's a big topic. It has to do with what this means in JavaScript.

ALL functions have an implicit parameter called this. How this is set when calling a function depends on how that function is called.

Take

function foo() { console.log(this); }

If you call it normally

function foo() { console.log(this); }
foo();

this will be the global object.

If you're in strict mode

`use strict`;
function foo() { console.log(this); }
foo();

// or

function foo() {
   `use strict`;
   console.log(this);
 }
foo();

It will be undefined

You can set this directly using call or apply

function foo(msg) { console.log(msg, this); }

const obj1 = {abc: 123}
const obj2 = {def: 456}

foo.call(obj1, 'hello');  // prints Hello {abc: 123}
foo.apply(obj2, ['hi']);  // prints Hi {def: 456}

You can also set this implicitly using the dot operator .

function foo(msg) { console.log(msg, this); }
const obj = {
   abc: 123,
   bar: foo,
}
obj.bar('Hola');  // prints Hola {abc:123, bar: f}

A problem comes up when you want to use a function as a callback or a listener. You make class and want to assign a function as the callback that accesses an instance of the class.

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name);  // won't work
    }); 
  }
}

The code above will not work because when the element fires the event and calls the function the this value will not be the instance of the class.

One common way to solve that problem is to use .bind

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name); 
    }.bind(this); // <=========== ADDED! ===========
  }
}

Because the arrow syntax does the same thing we can write

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click',() => {
       console.log(this.name); 
    });
  }
}

bind effectively makes a new function. If bind did not exist you could basically make your own like this

function bind(functionToBind, valueToUseForThis) {
  return function(...args) {
    functionToBind.call(valueToUseForThis, ...args);
  };
}

In older JavaScript without the spread operator it would be

function bind(functionToBind, valueToUseForThis) {
  return function() {
    functionToBind.apply(valueToUseForThis, arguments);
  };
}

Understanding that code requires an understanding of closures but the short version is bind makes a new function that always calls the original function with the this value that was bound to it. Arrow functions do the same thing since they are a shortcut for bind(this)

Getting multiple keys of specified value of a generic Dictionary?

Dictionary class is not optimized for this case, but if you really wanted to do it (in C# 2.0), you can do:

public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)
{
   List<TKey> ks = new List<TKey>();
   foreach(TKey k in dict.Keys)
   {
      if (dict[k] == val) { ks.Add(k); }
   }
   return ks;
}

I prefer the LINQ solution for elegance, but this is the 2.0 way.

What is this Javascript "require"?

You know how when you are running JavaScript in the browser, you have access to variables like "window" or Math? You do not have to declare these variables, they have been written for you to use whenever you want.

Well, when you are running a file in the Node.js environment, there is a variable that you can use. It is called "module" It is an object. It has a property called "exports." And it works like this:

In a file that we will name example.js, you write:

example.js

module.exports = "some code";

Now, you want this string "some code" in another file.

We will name the other file otherFile.js

In this file, you write:

otherFile.js

let str = require('./example.js')

That require() statement goes to the file that you put inside of it, finds whatever data is stored on the module.exports property. The let str = ... part of your code means that whatever that require statement returns is stored to the str variable.

So, in this example, the end-result is that in otherFile.js you now have this:

let string = "some code";

  • or -

let str = ('./example.js').module.exports

Note:

the file-name that is written inside of the require statement: If it is a local file, it should be the file-path to example.js. Also, the .js extension is added by default, so I didn't have to write it.

You do something similar when requiring node.js libraries, such as Express. In the express.js file, there is an object named 'module', with a property named 'exports'.

So, it looks something like along these lines, under the hood (I am somewhat of a beginner so some of these details might not be exact, but it's to show the concept:

express.js

module.exports = function() {
    //It returns an object with all of the server methods
    return {
        listen: function(port){},
        get: function(route, function(req, res){}){}
     }
}

If you are requiring a module, it looks like this: const moduleName = require("module-name");

If you are requiring a local file, it looks like this: const localFile = require("./path/to/local-file");

(notice the ./ at the beginning of the file name)


Also note that by default, the export is an object .. eg module.exports = {} So, you can write module.exports.myfunction = () => {} before assigning a value to the module.exports. But you can also replace the object by writing module.exports = "I am not an object anymore."

Dynamically change color to lighter or darker by percentage CSS (Javascript)

I know it's late but, you could use a wrapper to your buttons and change a rgba color function opacity level, as said in other answers but with no explicit example.

Here's a pen:

https://codepen.io/aronkof/pen/WzGmjR

_x000D_
_x000D_
#wrapper {_x000D_
  width: 50vw;_x000D_
  height: 50vh;_x000D_
  background-color: #AAA;_x000D_
  margin: 20px auto;_x000D_
  border-radius: 5px;_x000D_
  display: grid;_x000D_
  place-items: center;_x000D_
} _x000D_
_x000D_
.btn-wrap {_x000D_
  background-color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
button {_x000D_
  transition: all 0.6s linear;_x000D_
  background-color: rgba(0, 255, 0, 1);_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  color: #fff;_x000D_
  padding: 50px;_x000D_
  font-weight: 700;_x000D_
  font-size: 2em;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  background-color: rgba(0, 255, 0, .5);_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div class="btn-wrap">_x000D_
    <button class="btn">HEY!</buutton>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python strftime - date without leading 0?

Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try man strftime and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)

I would try using a new-style datetime object instead, which has attributes like t.year and t.month and t.day, and put those through the normal, high-powered formatting of the % operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting.

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

Using an image caption in Markdown Jekyll

I know this is an old question but I thought I'd still share my method of adding image captions. You won't be able to use the caption or figcaption tags, but this would be a simple alternative without using any plugins.

In your markdown, you can wrap your caption with the emphasis tag and put it directly underneath the image without inserting a new line like so:

![](path_to_image)
*image_caption*

This would generate the following HTML:

<p>
    <img src="path_to_image" alt>
    <em>image_caption</em>
</p>

Then in your CSS you can style it using the following selector without interfering with other em tags on the page:

img + em { }

Note that you must not have a blank line between the image and the caption because that would instead generate:

<p>
    <img src="path_to_image" alt>
</p>
<p>
    <em>image_caption</em>
</p>

You can also use whatever tag you want other than em. Just make sure there is a tag, otherwise you won't be able to style it.

HTML for the Pause symbol in audio and video control

▐▐  is HTML and is made with this code: &#9616;&#9616;.

Here's an example JSFiddle.

jquery ui Dialog: cannot call methods on dialog prior to initialization

This is also some work around:

$("div[aria-describedby='divDialog'] .ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close").click();

Face recognition Library

You can try open MVG library, It can be used for multiple interfaces too.

node.js execute system command synchronously

Node.js (since version 0.12 - so for a while) supports execSync:

child_process.execSync(command[, options])

You can now directly do this:

const execSync = require('child_process').execSync;
code = execSync('node -v');

and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync now.

How to return multiple values?

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

View list of all JavaScript variables in Google Chrome Console

Is this the kind of output you're looking for?

for(var b in window) { 
  if(window.hasOwnProperty(b)) console.log(b); 
}

This will list everything available on the window object (all the functions and variables, e.g., $ and jQuery on this page, etc.). Though, this is quite a list; not sure how helpful it is...

Otherwise just do window and start going down its tree:

window

This will give you DOMWindow, an expandable/explorable object.

How do I escape a string inside JavaScript code inside an onClick handler?

Another interesting solution might be to do this:

<a href="#" itemid="<%itemid%>" itemname="<%itemname%>" onclick="SelectSurveyItem(this.itemid, this.itemname); return false;">Select</a>

Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.

Yes, this does create HTML that is strictly invalid. However, it is a valid technique, and all modern browsers support it.

If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded and have single-quotes escaped.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

I assume you are using gcc, to simply link object files do:

$ gcc -o output file1.o file2.o

To get the object-files simply compile using

$ gcc -c file1.c

this yields file1.o and so on.

If you want to link your files to an executable do

$ gcc -o output file1.c file2.c

Pure CSS to make font-size responsive based on dynamic amount of characters

The only way would probably be to set different widths for different screen sizes, but this approach is pretty inacurate and you should use a js solution.

h1 {
    font-size: 20px;
}

@media all and (max-device-width: 720px){
    h1 {
        font-size: 18px;
    }
}

@media all and (max-device-width: 640px){
    h1 {
        font-size: 16px;
    }
}

@media all and (max-device-width: 320px){
    h1 {
        font-size: 12px;
    }
}

Difference Between One-to-Many, Many-to-One and Many-to-Many?

I would explain that way:

OneToOne - OneToOne relationship

@OneToOne
Person person;

@OneToOne
Nose nose;

OneToMany - ManyToOne relationship

@OneToMany
Shepherd> shepherd;

@ManyToOne
List<Sheep> sheeps;

ManyToMany - ManyToMany relationship

@ManyToMany
List<Traveler> travelers;

@ManyToMany
List<Destination> destinations;

How to execute shell command in Javascript

...few year later...

ES6 has been accepted as a standard and ES7 is around the corner so it deserves updated answer. We'll use ES6+async/await with nodejs+babel as an example, prerequisites are:

Your example foo.js file may look like:

import { exec } from 'child_process';

/**
 * Execute simple shell command (async wrapper).
 * @param {String} cmd
 * @return {Object} { stdout: String, stderr: String }
 */
async function sh(cmd) {
  return new Promise(function (resolve, reject) {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        reject(err);
      } else {
        resolve({ stdout, stderr });
      }
    });
  });
}

async function main() {
  let { stdout } = await sh('ls');
  for (let line of stdout.split('\n')) {
    console.log(`ls: ${line}`);
  }
}

main();

Make sure you have babel:

npm i babel-cli -g

Install latest preset:

npm i babel-preset-latest

Run it via:

babel-node --presets latest foo.js

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

How to configure welcome file list in web.xml

You need to put the JSP file in /index.jsp instead of in /WEB-INF/jsp/index.jsp. This way the whole servlet is superflous by the way.

WebContent
 |-- META-INF
 |-- WEB-INF
 |    `-- web.xml
 `-- index.jsp

If you're absolutely positive that you need to invoke a servlet this strange way, then you should map it on an URL pattern of /index.jsp instead of /index. You only need to change it to get the request dispatcher from request instead of from config and get rid of the whole init() method.

In case you actually intend to have a "home page servlet" (and thus not a welcome file — which has an entirely different purpose; namely the default file which sould be served when a folder is being requested, which is thus not specifically the root folder), then you should be mapping the servlet on the empty string URL pattern.

<servlet-mapping>
    <servlet-name>index</servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>

See also Difference between / and /* in servlet mapping url pattern.

Excel Define a range based on a cell value

Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.

=SUM(A1:INDIRECT(CONCATENATE("A",C5)))

I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.

ExecuteNonQuery doesn't return results

The ExecuteNonQuery method is used for SQL statements that are not queries, such as INSERT, UPDATE, ... You want to use ExecuteScalar or ExecuteReader if you expect your statement to return results (i.e. a query).

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

How to watch and compile all TypeScript sources?

Technically speaking you have a few options here:

If you are using an IDE like Sublime Text and integrated MSN plugin for Typescript: http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspx you can create a build system which compile the .ts source to .js automatically. Here is the explanation how you can do it: How to configure a Sublime Build System for TypeScript.

You can define even to compile the source code to destination .js file on file save. There is a sublime package hosted on github: https://github.com/alexnj/SublimeOnSaveBuild which make this happen, only you need to include the ts extension in the SublimeOnSaveBuild.sublime-settings file.

Another possibility would be to compile each file in the command line. You can compile even multiple files at once by separating them with spaces like so: tsc foo.ts bar.ts. Check this thread: How can I pass multiple source files to the TypeScript compiler?, but i think the first option is more handy.

Python class input argument

Python Classes

class name:
    def __init__(self, name):
        self.name = name
        print("name: "+name)

Somewhere else:

john = name("john")

Output:
name: john

Execute Insert command and return inserted Id in Sql

SQL Server stored procedure:

CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
    @na varchar(50),
    @occ varchar(50),
    @New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Mem_Basic
    VALUES (@na, @occ)

    SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END

C# code:

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    // values 0 --> -99 are SQL reserved.
    int new_MEM_BASIC_ID = -1971;   
    SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
    SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);

    outPutVal.Direction = ParameterDirection.Output;
    cmd.Parameters.Add(outPutVal);
    cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
    cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;

    SQLconn.Open();
    cmd.ExecuteNonQuery();
    SQLconn.Close();

    if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
        return new_MEM_BASIC_ID;
}

I hope these will help to you ....

You can also use this if you want ...

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    using (SqlConnection con=new SqlConnection(Config.ConnectionString))
    {
        int newID;
        var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";

        using(SqlCommand cmd=new SqlCommand(cmd, con))
        {
            cmd.Parameters.AddWithValue("@na", Mem_NA);
            cmd.Parameters.AddWithValue("@occ", Mem_Occ);

            con.Open();
            newID = (int)insertCommand.ExecuteScalar();

            if (con.State == System.Data.ConnectionState.Open) con.Close();
                return newID;
        }
    }
}

How do I get into a Docker container's shell?

$ docker exec -it <Container-Id> /bin/bash

Or depending on the shell, it can be

$ docker exec -it <Container-Id> /bin/sh

You can get the container-Id via docker ps command

-i = interactive

-t = to allocate a psuedo-TTY

What's the difference between UTF-8 and UTF-8 without BOM?

When you want to display information encoded in UTF-8 you may not face problems. Declare for example an HTML document as UTF-8 and you will have everything displayed in your browser that is contained in the body of the document.

But this is not the case when we have text, CSV and XML files, either on Windows or Linux.

For example, a text file in Windows or Linux, one of the easiest things imaginable, it is not (usually) UTF-8.

Save it as XML and declare it as UTF-8:

<?xml version="1.0" encoding="UTF-8"?>

It will not display (it will not be be read) correctly, even if it's declared as UTF-8.

I had a string of data containing French letters, that needed to be saved as XML for syndication. Without creating a UTF-8 file from the very beginning (changing options in IDE and "Create New File") or adding the BOM at the beginning of the file

$file="\xEF\xBB\xBF".$string;

I was not able to save the French letters in an XML file.

How might I extract the property values of a JavaScript object into an array?

Maybe a bit verbose, but robust and fast

var result = [];
var keys = Object.keys(myObject);
for (var i = 0, len = keys.length; i < len; i++) {
    result.push(myObject[keys[i]]);
}

How to convert timestamp to datetime in MySQL?

DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`

This is the ultimate solution if the given date is in encoded format like 1300464000

Get and Set Screen Resolution

in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

Select last row in MySQL

SELECT * FROM adds where id=(select max(id) from adds);

This query used to fetch the last record in your table.

PHP sessions that have already been started

Simply use if statement

 if(!isset($_SESSION)) 
     { 
         session_start(); 
     }

or

check the session status with session_status that Returns the current session status and if current session is already working then return with nothing else if session not working start the session


session_status() === PHP_SESSION_ACTIVE ?: session_start();

Better way to convert file sizes in Python

Here my two cents, which permits casting up and down, and adds customizable precision:

def convertFloatToDecimal(f=0.0, precision=2):
    '''
    Convert a float to string of decimal.
    precision: by default 2.
    If no arg provided, return "0.00".
    '''
    return ("%." + str(precision) + "f") % f

def formatFileSize(size, sizeIn, sizeOut, precision=0):
    '''
    Convert file size to a string representing its value in B, KB, MB and GB.
    The convention is based on sizeIn as original unit and sizeOut
    as final unit. 
    '''
    assert sizeIn.upper() in {"B", "KB", "MB", "GB"}, "sizeIn type error"
    assert sizeOut.upper() in {"B", "KB", "MB", "GB"}, "sizeOut type error"
    if sizeIn == "B":
        if sizeOut == "KB":
            return convertFloatToDecimal((size/1024.0), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size/1024.0**2), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0**3), precision)
    elif sizeIn == "KB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size/1024.0), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0**2), precision)
    elif sizeIn == "MB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0**2), precision)
        elif sizeOut == "KB":
            return convertFloatToDecimal((size*1024.0), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0), precision)
    elif sizeIn == "GB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0**3), precision)
        elif sizeOut == "KB":
            return convertFloatToDecimal((size*1024.0**2), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size*1024.0), precision)

Add TB, etc, as you wish.

HTTP GET in VBS

        strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
         "xmlns:tem=""http://tempuri.org/"">" &_
         "<soap:Header/>" &_
         "<soap:Body>" &_
            "<tem:Authorization>" &_
                "<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
                "<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
                "<tem:CVV2>"&123&"</tem:CVV2>" &_
                "<tem:strYR>"&23&"</tem:strYR>" &_
                "<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
            "</tem:Authorization>" &_
        "</soap:Body>" &_
        "</soap:Envelope>"

        EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
                "/trainingrite_epaysystem/tr_epaysys.asmx"



dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"

msgbox "REQUEST : " & strRequest
http.send strRequest

If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If

Call ParseTag(responseText,"AuthorizationResult")

Call CreateXMLEvidence(responseText,strRequest)

'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)

 ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
 Msgbox ResponseMessage

End Function

'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)

 Set fso=createobject("Scripting.FileSystemObject")
 Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
 Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)

 qfile.write ResponseXML
 qfile.close

 qfile1.write strRequest
 qfile1.close

End Function

Most pythonic way to delete a file which may not exist

if os.path.exists(filename): os.remove(filename)

is a one-liner.

Many of you may disagree - possibly for reasons like considering the proposed use of ternaries "ugly" - but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard "ugly".

How can I get the current PowerShell executing file?

If you only want the filename (not the full path) use this:

$ScriptName = $MyInvocation.MyCommand.Name

Load text file as strings using numpy.loadtxt()

Use genfromtxt instead. It's a much more general method than loadtxt:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

Using the file col.txt:

foo bar
cat dog
man wine

This gives:

[['foo' 'bar']
 ['cat' 'dog']
 ['man' 'wine']]

If you expect that each row has the same number of columns, read the first row and set the attribute filling_values to fix any missing rows.

How to connect PHP with Microsoft Access database

If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec() approach. Here is a simple example:

<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";

$connStr = 
        'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
        'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';

$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = 
        "SELECT AgentName FROM Agents " .
        "WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);

// query parameter value(s)
$params = array(
        5,
        'Homer'
        );

$sth->execute($params);

while ($row = $sth->fetch()) {
    echo $row['AgentName'] . "\r\n";
}

NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF. If you do need to support such characters then neither PDO_ODBC nor the old odbc_ functions will work; you'll need to use the solution described in this answer.

How to get the value of an input field using ReactJS?

Managed to get the input field value by doing something like this:

import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);

this.state = {
  username : ''
}

this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}


updateInput(event){
this.setState({username : event.target.value})
}


handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}



render(){
return (
    <div>
    <input type="text" onChange={this.updateInput}></input>
    <input type="submit" onClick={this.handleSubmit} ></input>
    </div>
  );
}
} 

//output
//Your input value is: x

Assign format of DateTime with data annotations?

Use EditorFor rather than TextBoxFor

Converting JSON to XML in Java

For json to xml use the following Jackson example:

final String str = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
ObjectMapper jsonMapper = new ObjectMapper();
JsonNode node = jsonMapper.readValue(str, JsonNode.class);
XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
StringWriter w = new StringWriter();
xmlMapper.writeValue(w, node);
System.out.println(w.toString());

Prints:

<?xml version='1.1' encoding='UTF-8'?>
<ObjectNode>
  <name>JSON</name>
  <integer>1</integer>
  <double>2.0</double>
  <boolean>true</boolean>
  <nested>
    <id>42</id>
  </nested>
  <array>1</array>
  <array>2</array>
  <array>3</array>
</ObjectNode>

To convert it back (xml to json) take a look at this answer https://stackoverflow.com/a/62468955/1485527 .

Passing string to a function in C - with or without pointers?

Assuming that you meant to write

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

How to get user's high resolution profile picture on Twitter?

for me the "workaround" solution was to remove the "_normal" from the end of the string

Check it out below:

How to set up default schema name in JPA configuration?

Use this

@Table (name = "Test", schema = "\"schema\"")

insteade of @Table (name = "Test", schema = "schema")

If you are on postgresql the request is :

SELECT * FROM "schema".test 

not :

SELECT * FROM schema.test

PS: Test is a table

How do I Set Background image in Flutter?

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

Docker - a way to give access to a host USB or serial device?

--device works until your USB device gets unplugged/replugged and then it stops working. You have to use cgroup devices.allow get around it.
You could just use -v /dev:/dev but that's unsafe as it maps all the devices from your host into the container, including raw disk devices and so forth. Basically this allows the container to gain root on the host, which is usually not what you want.
Using the cgroups approach is better in that respect and works on devices that get added after the container as started.

See details here: Accessing USB Devices In Docker without using --privileged

It's a bit hard to paste, but in a nutshell, you need to get the major number for your character device and send that to cgroup:

189 is the major number of /dev/ttyUSB*, which you can get with 'ls -l'. It may be different on your system than on mine:

root@server:~# echo 'c 189:* rwm' > /sys/fs/cgroup/devices/docker/$A*/devices.allow  
(A contains the docker containerID)

Then start your container like this:

docker run -v /dev/bus:/dev/bus:ro -v /dev/serial:/dev/serial:ro -i -t --entrypoint /bin/bash debian:amd64

without doing this, any newly plugged or rebooting device after the container started, will get a new bus ID and will not be allowed access in the container.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  $(window).scroll(function() {_x000D_
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
      }_x000D_
    });_x000D_
  }).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
    var min = 0.3;_x000D_
    var max = 0.7;_x000D_
    var threshold = 0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
      }_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
    var min=0.3, max=0.7, threshold=0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
      _x000D_
      /* Fade element in/out based on its visible percentage */_x000D_
      if (objectTop < windowTop) {_x000D_
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if (objectBottom > windowBottom) {_x000D_
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/5/)

Android - Spacing between CheckBox and text

Android 4.2 Jelly Bean (API 17) puts the text paddingLeft from the buttonDrawable (ints right edge). It also works for RTL mode.

Before 4.2 paddingLeft was ignoring the buttonDrawable - it was taken from the left edge of the CompoundButton view.

You can solve it via XML - set paddingLeft to buttonDrawable.width + requiredSpace on older androids. Set it to requiredSpace only on API 17 up. For example use dimension resources and override in values-v17 resource folder.

The change was introduced via android.widget.CompoundButton.getCompoundPaddingLeft();

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

How to generate a simple popup using jQuery

I use a jQuery plugin called ColorBox, it is

  1. Very easy to use
  2. lightweight
  3. customizable
  4. the nicest popup dialog I have seen for jQuery yet

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

How to use mouseover and mouseout in Angular 6

The Angular6 equivalent code should be:

app.component.html

<div (mouseover)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>

app.component.ts

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

Notice that there is no such thing as $scope anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.

Installing PG gem on OS X - failure to build native extension

For those who are not interested to use brew.

  1. Download PostgreSQL application.
  2. Follow the macOS default instruction to install it.
  3. It is advisable to run PostgreSQl.
  4. Run gem install pg -- --with-pg-config=/path/to/postgress/in/your/applications/folder/`
    • For example, in my machine it is /Applications/Postgres.app/Contents/Versions/12/bin/pg_config

How to get the list of all installed color schemes in Vim?

Another simpler way is while you are editing a file - tabe ~/.vim/colors/ ENTER Will open all the themes in a new tab within vim window.

You may come back to the file you were editing using - CTRL + W + W ENTER

Note: Above will work ONLY IF YOU HAVE a .vim/colors directory within your home directory for current $USER (I have 70+ themes)

[user@host ~]$ ls -l ~/.vim/colors | wc -l

72

sed with literal string--not input file

You have a single quotes conflict, so use:

 echo "A,B,C" | sed "s/,/','/g"

If using , you can do too (<<< is a here-string):

sed "s/,/','/g" <<< "A,B,C"

but not

sed "s/,/','/g"  "A,B,C"

because sed expect file(s) as argument(s)

EDIT:

if you use or any other ones :

echo string | sed ...

Git merge error "commit is not possible because you have unmerged files"

I've had a similar issue which boiled down to removing files under "unmerged paths"

Those files had to be removed using git rm

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

How to include !important in jquery

For those times when you need to use jquery to set !important properties, here is a plugin I build that will allow you to do so.

$.fn.important = function(key, value) {
    var q = Object.assign({}, this.style)
    q[key] = `${value} !important`;
    $(this).css("cssText", Object.entries(q).filter(x => x[1]).map(([k, v]) => (`${k}: ${v}`)).join(';'));
};

$('div').important('color', 'red');

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

On CYGwin, you can install this as a typical package in the first screen. Look for

libssl-devel

How to change 1 char in the string?

str = "M" + str.Substring(1);

If you'll do several such changes use a StringBuilder or a char[].

(The threshold of when StringBuilder becomes quicker is after about 5 concatenations or substrings, but note that grouped concatenations of a + "b" + c + d + "e" + f are done in a single call and compile-type concatenations of "a" + "b" + "c" don't require a call at all).

It may seem that having to do this is horribly inefficient, but the fact that strings can't be changes allows for lots of efficiency gains and other advantages such as mentioned at Why .NET String is immutable?

Converting Array to List

Old way but still working!

 int[] values = {1,2,3,4};
 List<Integer> list = new ArrayList<>(values.length);

 for(int valor : values) {
     list.add(valor);
 }

how to place last div into right top corner of parent div? (css)

You can simply add a right float to .block2 element and place it in the first position (this is very important).

Here is the code:

<html>
<head>
    <style type="text/css">
        .block1 {
            color: red;
            width: 100px;
            border: 1px solid green;
        }
        .block2 {
            color: blue;
            width: 70px;
            border: 2px solid black;
            position: relative;
            float: right;
        }
    </style>
</head>
<body>
    <div class='block1'>
        <div class='block2'>block2</div>
        <p>text</p>
        <p>text2</p>
    </div>
</body>

Regards...

Make body have 100% of the browser height

As an alternative to setting both the html and body element's heights to 100%, you could also use viewport-percentage lengths.

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

In this instance, you could use the value 100vh - which is the height of the viewport.

Example Here

body {
  height: 100vh;
  padding: 0;
}
body {
  min-height: 100vh;
  padding: 0;
}

This is supported in most modern browsers - support can be found here.

Generate random string/characters in JavaScript

A functional approach. This answer is only practical if the functional prerequisites can be leveraged in other parts of your app. The performance is probably junk, but it was super fun to write.

_x000D_
_x000D_
// functional prerequisites_x000D_
const U = f=> f (f)_x000D_
const Y = U (h=> f=> f (x=> h (h) (f) (x)))_x000D_
const comp = f=> g=> x=> f (g (x))_x000D_
const foldk = Y (h=> f=> y=> ([x, ...xs])=>_x000D_
  x === undefined ? y : f (y) (x) (y=> h (f) (y) (xs)))_x000D_
const fold = f=> foldk (y=> x=> k=> k (f (y) (x)))_x000D_
const map = f=> fold (y=> x=> [...y, f (x)]) ([])_x000D_
const char = x=> String.fromCharCode(x)_x000D_
const concat = x=> y=> y.concat(x)_x000D_
const concatMap = f=> comp (fold (concat) ([])) (map (f))_x000D_
const irand = x=> Math.floor(Math.random() * x)_x000D_
const sample = xs=> xs [irand (xs.length)]_x000D_
_x000D_
// range : make a range from x to y; [x...y]_x000D_
// Number -> Number -> [Number]_x000D_
const range = Y (f=> r=> x=> y=>_x000D_
  x > y ? r : f ([...r, x]) (x+1) (y)_x000D_
) ([])_x000D_
_x000D_
// srand : make random string from list or ascii code ranges_x000D_
// [(Range a)] -> Number -> [a]_x000D_
const srand = comp (Y (f=> z=> rs=> x=>_x000D_
  x === 0 ? z : f (z + sample (rs)) (rs) (x-1)_x000D_
) ([])) (concatMap (map (char)))_x000D_
_x000D_
// idGenerator : make an identifier of specified length_x000D_
// Number -> String_x000D_
const idGenerator = srand ([_x000D_
  range (48) (57),  // include 0-9_x000D_
  range (65) (90),  // include A-Z_x000D_
  range (97) (122)  // include a-z_x000D_
])_x000D_
_x000D_
console.log (idGenerator (6))  //=> TT688X_x000D_
console.log (idGenerator (10)) //=> SzaaUBlpI1_x000D_
console.log (idGenerator (20)) //=> eYAaWhsfvLDhIBID1xRh
_x000D_
_x000D_
_x000D_

In my opinion, it's hard to beat the clarity of idGenerator without adding magical, do-too-many-things functions.

A slight improvement could be

// ord : convert char to ascii code
// Char -> Number
const ord = x => x.charCodeAt(0)

// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
  range (ord('0')) (ord('9')),
  range (ord('A')) (ord('Z')),
  range (ord('a')) (ord('z'))
])

Have fun with it. Let me know what you like/learn ^_^

html script src="" triggering redirection with button

I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.

How can I open Java .class files in a human-readable way?

JAD and/or JADclipse Eclipse plugin, for sure.

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Does Index of Array Exist

It sounds very much like you're using an array to store different fields. This is definitely a code smell. I'd avoid using arrays as much as possible as they're generally not suitable (or needed) in high-level code.

Switching to a simple Dictionary may be a workable option in the short term. As would using a big property bag class. There are lots of options. The problem you have now is just a symptom of bad design, you should look at fixing the underlying problem rather than just patching the bad design so it kinda, sorta mostly works, for now.

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

How can I detect if a selector returns null?

The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length of the collection returned by the selector or check whether the first array element is 'undefined'.

You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

jQuery callback on image load (even when the image is cached)

By using jQuery to generate a new image with the image's src, and assigning the load method directly to that, the load method is successfully called when jQuery finishes generating the new image. This is working for me in IE 8, 9 and 10

$('<img />', {
    "src": $("#img").attr("src")
}).load(function(){
    // Do something
});

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

Regular Expressions: Search in list

Full Example (Python 3):
For Python 2.x look into Note below

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)

Prints:

['cat', 'wildcat', 'thundercat']

Note:

For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).

Python 3 code example
Python 2.x code example

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

Safely override C++ virtual functions

Your compiler may have a warning that it can generate if a base class function becomes hidden. If it does, enable it. That will catch const clashes and differences in parameter lists. Unfortunately this won't uncover a spelling error.

For example, this is warning C4263 in Microsoft Visual C++.

How to use setprecision in C++

#include <iomanip>
#include <iostream>

int main()
{
    double num1 = 3.12345678;
    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(2);
    std::cout << num1 << std::endl;
    return 0;
}

Copy files on Windows Command Line with Progress

You could easily write a program to do that, I've got several that I've written, that display bytes copied as the file is being copied. If you're interested, comment and I'll post a link to one.

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

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

I solved the problem by uninstalling NodeJs and gulp then re-installing both again.

To install gulp globally I executed the following command

npm install -g gulp

How to create a property for a List<T>

public class MyClass<T>
{
  private List<T> list;

  public List<T> MyList { get { return list; } set { list = value; } }
}

Then you can do something like

MyClass<int> instance1 = new MyClass<int>();
List<int> integers = instance1.MyList;

MyClass<Person> instance2 = new MyClass<Person>();
IEnumerable<Person> persons = instance2.MyList;

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

How to obtain Certificate Signing Request

To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.

Create a CSR file. In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.

Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.

In the Certificate Information window, enter the following information: In the User Email Address field, enter your email address. In the Common Name field, create a name for your private key (e.g., John Doe Dev Key). The CA Email Address field should be left empty. In the "Request is" group, select the "Saved to disk" option. Click Continue within Keychain Access to complete the CSR generating process.

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

How to change the button text of <input type="file" />?

You can put an image instead, and do it like this:

HTML:

<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1"  name="file1" style="display:none" />

JQuery:

$("#upfile1").click(function () {
    $("#file1").trigger('click');
});

CAVEAT: In IE9 and IE10 if you trigger the onClick in a file input via javascript, the form will be flagged as 'dangerous' and cannot be submitted with javascript, not sure if it can be submitted traditionally.

How to change collation of database, table, column?

You can change the CHARSET and COLLATION of all your tables through PHP script as follows. I like the answer of hkasera but the problem with it is that the query runs twice on each table. This code is almost the same except using MySqli instead of mysql and prevention of double querying. If I could vote up, I would have voted hkasera's answer up.

<?php
$conn1=new MySQLi("localhost","user","password","database");
if($conn1->connect_errno){
    echo mysqli_connect_error();
    exit;
}
$res=$conn1->query("show tables") or die($conn1->error);
while($tables=$res->fetch_array()){
    $conn1->query("ALTER TABLE $tables[0] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") or die($conn1->error);
}
echo "The collation of your database has been successfully changed!";

$res->free();
$conn1->close();

?>

SQL query for extracting year from a date

How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE

React - How to get parameter value from query string?

React Router 5.1+

5.1 introduced various hooks like useLocation and useParams that could be of use here.

Example:

<Route path="/test/:slug" component={Dashboard} />

Then if we visited say

http://localhost:3000/test/signin?_k=v9ifuf&__firebase_request_key=blablabla

You could retrieve it like

import { useLocation } from 'react-router';
import queryString from 'query-string';

const Dashboard: React.FC = React.memo((props) => {
    const location = useLocation();

    console.log(queryString.parse(location.search));

    // {__firebase_request_key: "blablabla", _k: "v9ifuf"}

    ...

    return <p>Example</p>;
}

MySQL server has gone away - in exactly 60 seconds

It happens if the connection was open for quite sometime but no action was done in the MySQL server. In that case, connection timeout occurs with the error "MySQL server has gone away". The answers above may work and may not work. Even the accepted answer did not work for me. So I tried a trick and it worked fine for me. Logically, in order to avoid this error, we have to keep the MySQL connection running or in short, keep it alive. Assume that we are trying to Bulk insert 250k records. Generally it takes time to create parse data from somewhere and make Bulk query and then insert. In this scenario, most of us use a loop to create the SQL string. So let's count the iteration number and make a dummy database call after a certain iteration. It will keep the connection alive.

for(int i = 0, size = somedatalist.length; i < size; ++i){

     // build the Bulk insert query string

     if((i%10000)==0){
         // make a dummy call like `SELECT * FROM log LIMIT 1`
         // it will keep the connection alive
     }
}
// Execute bulk insert

No templates in Visual Studio 2017

If you have installed .NET desktop development and still you can't see the templates, then VS is probably getting the templates from your custom templates folder and not installed.

To fix that, copy the installed templates folder to custom.

This is your "installed" folder

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates

This is your "custom" folder

C:\Users[your username]\Documents\Visual Studio\2017\Templates\ProjectTemplates

Typically this happens when you are at the office and you are running VS as an administrator and visual studio is confused how to merge both of them and if you notice they don't have the same folder structure and folder names.. One is CSHARP and the other C#....

I didn't have the same problem when I installed VS 2017 community edition at home though. This happened when I installed visual studio 2017 "enterprise" edition.

Singular matrix issue with Numpy

Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

numpy.linalg.svd numpy.linalg.qr

How to serialize object to CSV file?

For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.

asp.net: Invalid postback or callback argument

After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.

This caused the app pool to give up and reply with the exception noted in the question.

Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

How to recover a dropped stash in Git?

git fsck --unreachable | grep commit should show the sha1, although the list it returns might be quite large. git show <sha1> will show if it is the commit you want.

git cherry-pick -m 1 <sha1> will merge the commit onto the current branch.

Undefined reference to vtable

The GCC FAQ has an entry on it:

The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual [class.dtor]/7.

Therefore, you need to provide a definition for the virtual destructor:

virtual ~CDasherModule()
{ };

show/hide html table columns using css

One line of code using jQuery:

$('td:nth-child(2)').hide();

// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();

Source: Hide a Table Column with a Single line of jQuery code

npm install private github repositories by dependency in package.json

There are multiple ways to do it as people point out, but the shortest versions are:

// from master
"depName": "user/repo",

// specific branch
"depName": "user/repo#branch",

// specific commit
"depName": "user/repo#commit",

// private repo
"depName": "git+https://[TOKEN]:[email protected]/user/repo.git"

e.g.

"dependencies" : {
  "hexo-renderer-marked": "amejiarosario/dsa.jsd#book",
  "hexo-renderer-marked": "amejiarosario/dsa.js#8ea61ce",
  "hexo-renderer-marked": "amejiarosario/dsa.js",
}

What is the difference between Integer and int in Java?

int is a primitive data type while Integer is a Reference or Wrapper Type (Class) in Java.

after java 1.5 which introduce the concept of autoboxing and unboxing you can initialize both int or Integer like this.

int a= 9
Integer a = 9 // both valid After Java 1.5.

why Integer.parseInt("1"); but not int.parseInt("1"); ??

Integer is a Class defined in jdk library and parseInt() is a static method belongs to Integer Class

So, Integer.parseInt("1"); is possible in java. but int is primitive type (assume like a keyword) in java. So, you can't call parseInt() with int.

HTML5 Canvas Rotate Image

The other solution works great for square images. Here is a solution that will work for an image of any dimension. The canvas will always fit the image rather than the other solution which may cause portions of the image to be cropped off.

var canvas;

var angleInDegrees=0;

var image=document.createElement("img");
image.onload=function(){

    drawRotated(0);
}
image.src="http://greekgear.files.wordpress.com/2011/07/bob-barker.jpg";

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
});

$("#counterclockwise").click(function(){ 
    if(angleInDegrees == 0)
        angleInDegrees = 270;
    else
        angleInDegrees-=90 % 360;
    drawRotated(angleInDegrees);
});

function drawRotated(degrees){
    if(canvas) document.body.removeChild(canvas);

    canvas = document.createElement("canvas");
    var ctx=canvas.getContext("2d");
    canvas.style.width="20%";

    if(degrees == 90 || degrees == 270) {
        canvas.width = image.height;
        canvas.height = image.width;
    } else {
        canvas.width = image.width;
        canvas.height = image.height;
    }

    ctx.clearRect(0,0,canvas.width,canvas.height);
    if(degrees == 90 || degrees == 270) {
        ctx.translate(image.height/2,image.width/2);
    } else {
        ctx.translate(image.width/2,image.height/2);
   }
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-image.width/2,-image.height/2);

    document.body.appendChild(canvas);
}

http://jsfiddle.net/6ZsCz/1588/

Insert picture/table in R Markdown

In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmdheader looks like

---
title       : French TER (regional train) monthly regularity
subtitle    : since January 2013
author      : brigasnuncamais
job         : Business Intelligence / Data Scientist consultant
framework   : impressjs     # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      # 
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

subdirs are:

/assets /css    /impress-demo.css
        /fig    /unnamed-chunk-1-1.png (generated by included R code)
        /img    /SS850452.png (my image used as background)
        /js     /impress.js
        /layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
        /libraries  /frameworks /impressjs
                                /io2012
                    /highlighters   /highlight.js
                                    /impress.js
index.Rmd

A slide with image in background code snippet would be in my .Rmd:

<div id="bg">
  <img src="assets/img/SS850452.png" alt="">
</div>  

Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

How to locate the Path of the current project directory in Java (IDE)?

YOU CANT.

Java-Projects does not have ONE path! Java-Projects has multiple pathes even so one Class can have multiple locations in different classpath's in one "Project".

So if you have a calculator.jar located in your JRE/lib and one calculator.jar with the same classes on a CD: if you execute the calculator.jar the classes from the CD, the java-vm will take the classes from the JRE/lib!

This problem often comes to programmers who like to load resources deployed inside of the Project. In this case,

System.getResource("/likebutton.png") 

is taken for example.

Angularjs prevent form submission when input validation fails

You can do:

<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">

No need for controller checks.

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

Play audio with Python

It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

How to programmatically round corners and set random background colors

Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( R.id.my_view );
 view.setBackground(shape);

Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius because ShapeDrawable DOES NOT provide any such method.

How To Set Text In An EditText

String string="this is a text";
editText.setText(string)

I have found String to be a useful Indirect Subclass of CharSequence

http://developer.android.com/reference/android/widget/TextView.html find setText(CharSequence text)

http://developer.android.com/reference/java/lang/CharSequence.html

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

How can I get query parameters from a URL in Vue.js?

If your url looks something like this:

somesite.com/something/123

Where '123' is a parameter named 'id' (url like /something/:id), try with:

this.$route.params.id

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

Dots in URL causes 404 with ASP.NET mvc and IIS

Depending on how important it is for you to keep your URI without querystrings, you can also just pass the value with dots as part of the querystring, not the URI.

E.g. www.example.com/people?name=michael.phelps will work, without having to change any settings or anything.

You lose the elegance of having a clean URI, but this solution does not require changing or adding any settings or handlers.

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

How do I encode and decode a base64 string?

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

using System;

namespace Service.Support
{
    public static class Base64
    {
        public static string ToBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return Convert.ToBase64String(textAsBytes);
        }

        public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
        {
            if (encodedText == null)
            {
                decodedText = null;
                return false;
            }

            try
            {
                byte[] textAsBytes = Convert.FromBase64String(encodedText);
                decodedText = encoding.GetString(textAsBytes);
                return true;
            }
            catch (Exception)
            {
                decodedText = null;
                return false;   
            }
        }
    }
}

Spring Boot - Loading Initial Data

In Spring Boot 2 data.sql was not working with me as in spring boot 1.5

import.sql

In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop).

Note very important if you insert Keys cannot be duplicated do not use ddl-auto property is set to update because with each restart will insert same data again

For more information you vist spring websit

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

EL interprets ${bean.propretyName} as described - the propertyName becomes getPropertyName() on the assumption you are using explicit or implicit methods of generating getter/setters

You can override this behavior by explicitly identifying the name as a function: ${bean.methodName()} This calls the function method Name() directly without modification.

It isn't always true that your accessors are named "get...".

Delete a row in Excel VBA

Something like this will do it:

Rows("12:12").Select
Selection.Delete

So in your code it would look like something like this:

Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.

text-shadow : 0 0 0 #your-font-color;

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Similar problem: Find <button>Advanced...</button>

Maybe this will give you some ideas (please transfer the concept from Java to Python):

wait.until(ExpectedConditions.elementToBeClickable(//
    driver.findElements(By.tagName("button")).stream().filter(i -> i.getText().equals("Advanced...")).findFirst().get())).click();

Does Java have something like C#'s ref and out keywords?

No, Java doesn't have something like C#'s ref and out keywords for passing by reference.

You can only pass by value in Java. Even references are passed by value. See Jon Skeet's page about parameter passing in Java for more details.

To do something similar to ref or out you would have to wrap your parameters inside another object and pass that object reference in as a parameter.

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

Random strings in Python

random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53. result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

Enjoy. ;)

Create new user in MySQL and give it full access to one database

$ mysql -u root -p -e "grant all privileges on dbTest.* to
`{user}`@`{host}` identified by '{long-password}'; flush privileges;"

ignore -p option, if mysql user has no password or just press "[Enter]" button to by-pass. strings surrounded with curly braces need to replaced with actual values.

BOOLEAN or TINYINT confusion

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html

YouTube Video Embedded via iframe Ignoring z-index?

Just add one of these two to the src url:

&wmode=Opaque

&wmode=transparent

<iframe id="videoIframe" width="500" height="281" src="http://www.youtube.com/embed/xxxxxx?rel=0&wmode=transparent" frameborder="0" allowfullscreen></iframe>

Changing every value in a hash in Ruby

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h

"multiple target patterns" Makefile error

I had it on the Makefile

MAPS+=reverse/db.901:550:2001.ip6.arpa 
lastserial:  ${MAPS}
    ./updateser ${MAPS}

It's because of the : in the file name. I solved this with

                      -------- notice
                     /    /
                    v    v
MAPS+=reverse/db.901\:550\:2001.ip6.arpa
lastserial:  ${MAPS}
    ./updateser ${MAPS}

Convert a python UTC datetime to a local datetime using only python standard library?

You can't do it with only the standard library as the standard library doesn't have any timezones. You need pytz or dateutil.

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.

Disable color change of anchor tag when visited

Either delete the selector or set it to the same color as your text appears normally.

Reading and writing value from a textfile by using vbscript code

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")

' read file
data = inFile.ReadAll
inFile.Close

' write file
outFile.write (data)
outFile.Close

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

Convert normal date to unix timestamp

new Date('2012.08.10').getTime() / 1000

Check the JavaScript Date documentation.

Document directory path of Xcode Device Simulator

update: Xcode 11.5 • Swift 5.2

if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.path {
    print(documentsPath)   // "var/folder/.../documents\n" copy the full path
}

Go to your Finder press command-shift-g (or Go > Go to Folder... under the menu bar) and paste that full path "var/folder/.../documents" there and press go.

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

You have to patch catalina.jar, as this is version number the WTP adapter looks at. It's a quite useless check, and the adapter should allow you to start the server anyway, but nobody has though of that yet.

For years and with every version of Tomcat this is always a problem.

To patch you can do the following:

  • cd [tomcat or tomee home]/lib
  • mkdir catalina
  • cd catalina/
  • unzip ../catalina.jar
  • vim org/apache/catalina/util/ServerInfo.properties

Make sure it looks like the following (the version numbers all need to start with 8.0):

server.info=Apache Tomcat/8.0.0
server.number=8.0.0
server.built=May 11 2016 21:49:07 UTC

Then:

  • jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties
  • cd ..
  • rm -rf catalina

Recursively add the entire folder to a repository

I also had the same issue and I do not have .gitignore file. My problem was solved with the following way. This took all sub-directories and files.

git add <directory>/*