text:
#Writing your first Django app

## Table

[#Part2](#part2)
[#Part3](#part3)
[#Part4](#part4)

### Goal

    we’ll walk you through the creation of a basic poll application.

it has two part.

- A public site that lets people view polls and vote in them.

## 1. step - Create probject

command :

django-admin startproject `projectName`

ex.

>> django-admin startproject mysite

They will create

    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py

- The outer mysite/ root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
- manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.
- The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).
- mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. (Read more about packages in the official Python docs if you’re a Python beginner.)
- mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
- mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.
- mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

## 2. Step - Database setup

    python manage.py migrate

>>>> Why are you need migrate?

>>>> What happen if you do migrate?

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (we’ll cover those later).

## 3. Step - Run server

    python manage.py runserver

## 4. Step - Create Model

command

    python manage.py startapp `AppName`

ex.

    python manage.py startapp polls

polls/models.py

    from django.db import models

    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')

    class Choice(models.Model):
        question = models.ForeignKey(Question)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)

Picture

    Question
        text(Char)
        date(Time)

    Choice
        question(Qestion)
        text(Char)
        votes(Integer)

>>>> What kind of type that i have?

Ref : [Model Doc](https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model)

Modify setting

    mysite/setting.py

    INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    `'polls',`
    )

### Update

Command

    python manage.py makemigrations appName

ex.
    python manage.py makemigrations polls

You will get message:

    Migrations for 'polls':
        0001_initial.py:
            - Create model Question
            - Create model Choice
            - Add field question to choice

run migrate again to create those model tables in your database:

    python manage.py migrate

###小節

- Change your models (in models.py).
- Run python manage.py makemigrations to create migrations for those changes
- Run python manage.py migrate to apply those changes to the database.

## Playing with the API

    Python manage.py shell

database api:

    >>> from polls.models import Question, Choice   # Import the model classes we just wrote.

    # No questions are in the system yet.
    >>> Question.objects.all()
    []

    # Create a new Question.
    # Support for time zones is enabled in the default settings file, so
    # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
    # instead of datetime.datetime.now() and it will do the right thing.
    >>> from django.utils import timezone
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())

    # Save the object into the database. You have to call save() explicitly.
    >>> q.save()

    # Now it has an ID. Note that this might say "1L" instead of "1", depending
    # on which database you're using. That's no biggie; it just means your
    # database backend prefers to return integers as Python long integer
    # objects.
    >>> q.id
    1

    # Access model field values via Python attributes.
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

    # Change values by changing the attributes, then calling save().
    >>> q.question_text = "What's up?"
    >>> q.save()

    # objects.all() displays all the questions in the database.
    >>> Question.objects.all()
    [<Question: Question object>]

Stop , this has `[<Question: Question object>]`, it need be text.

>>>> Notice : if you run this shell has some problem.

>>>> Delete the sqlite file, and rerun the command start by `python manager.py makemigrations appName` and `python manager.py migrate`

### Convert text

polls/models.py

    from django.db import models

    class Question(models.Model):
        # ...
        def __str__(self):              # __unicode__ on Python 2
            return self.question_text

    class Choice(models.Model):
        # ...
        def __str__(self):              # __unicode__ on Python 2
            return self.choice_text

### add new function

polls/models.py

    import datetime

    from django.db import models
    from django.utils import timezone

    class Question(models.Model):
        # ...
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

### Second Parts - Database API

    >>> from polls.models import Question, Choice

    # Make sure our __str__() addition worked.
    >>> Question.objects.all()
    [<Question: What's up?>]

    # Django provides a rich database lookup API that's entirely driven by
    # keyword arguments.
    >>> Question.objects.filter(id=1)
    [<Question: What's up?>]
    >>> Question.objects.filter(question_text__startswith='What')
    [<Question: What's up?>]

    # Get the question that was published this year.
    >>> from django.utils import timezone
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: What's up?>

    # Request an ID that doesn't exist, this will raise an exception.
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Question matching query does not exist.

    # Lookup by a primary key is the most common case, so Django provides a
    # shortcut for primary-key exact lookups.
    # The following is identical to Question.objects.get(id=1).
    >>> Question.objects.get(pk=1)
    <Question: What's up?>

    # Make sure our custom method worked.
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True

    # Give the Question a couple of Choices. The create call constructs a new
    # Choice object, does the INSERT statement, adds the choice to the set
    # of available choices and returns the new Choice object. Django creates
    # a set to hold the "other side" of a ForeignKey relation
    # (e.g. a question's choice) which can be accessed via the API.
    >>> q = Question.objects.get(pk=1)

    # Display any choices from the related object set -- none so far.
    >>> q.choice_set.all()
    []

    # Create three choices.
    >>> q.choice_set.create(choice_text='Not much', votes=0)
    <Choice: Not much>
    >>> q.choice_set.create(choice_text='The sky', votes=0)
    <Choice: The sky>
    >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

    # Choice objects have API access to their related Question objects.
    >>> c.question
    <Question: What's up?>

    # And vice versa: Question objects get access to Choice objects.
    >>> q.choice_set.all()
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    >>> q.choice_set.count()
    3

    # The API automatically follows relationships as far as you need.
    # Use double underscores to separate relationships.
    # This works as many levels deep as you want; there's no limit.
    # Find all Choices for any question whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

    # Let's delete one of the choices. Use delete() for that.
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()

# Part2

>> Django’s automatically-generated admin site

## Creating an admin user

create user

    python manage.py createsuperuser

## Start the development server

    python manage.py runserver

    http://<IP_ADDRESS>:8000/admin/

## Make the poll app modifiable in the admin

>> Add Field into admin page.

polls/admin.py

    from django.contrib import admin

    from .models import Question

    admin.site.register(Question)

## Customize the admin form

>> You can design your expect order.

polls/admin.py

    from django.contrib import admin

    from .models import Question

    class QuestionAdmin(admin.ModelAdmin):
        fields = ['pub_date', 'question_text']

    admin.site.register(Question, QuestionAdmin)

### fields change order

    class QuestionAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question_text']}),
            ('Date information', {'fields': ['pub_date']}),
        ]

None and 'Date information' is field name.

### show and hide dataset

    class QuestionAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question_text']}),
            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        ]

`{'fields': ['pub_date'], 'classes': ['collapse']})` is value.

The field can collapse is use `'classes': ['collapse']`.

## Adding related objects

Add Choice

admin.py

    from .models import Choice, Question

    admin.site.register(Choice)

Add Choice into Question

    from django.contrib import admin

    from .models import Choice, Question

    class ChoiceInline(admin.StackedInline):
        model = Choice
        extra = 3

    class QuestionAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question_text']}),
            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        ]
        inlines = [ChoiceInline]

    admin.site.register(Question, QuestionAdmin)

Change component form

    ChoiceInline(admin.TabularInline)

StackedInline

    Item
        1
        2
        3
    Item
        1
        2
        3

    Item
        1
        2

TabularInline

    Item
        1   2
    Item
        1   2
    Item
        1   2

## Customize the admin change list

    class QuestionAdmin(admin.ModelAdmin):
        # ...
        list_display = ('question_text', 'pub_date')

polls/admin.py

    list_filter = ['pub_date']

# Part3

>> We’re continuing the Web-poll application and will focus on creating the public interface – “views.”

## Philosophy

A view is a "type" of Web page in your Django application that serves a function and has a tempalte.

Ex. In a blog application, you might have the following views:

- Blog homepage – displays the latest few entries.
- Entry “detail” page – permalink page for a single entry.
- Year-based archive page – displays all months with entries in the given year.
- Month-based archive page – displays all days with entries in the given month.
- Day-based archive page – displays all entries in the given day.
- Comment action – handles posting comments to a given entry.

In our poll application, we’ll have four views:

- Question “index” page – displays the latest few questions.
- Question “detail” page – displays a question text, with no results but with a form to vote.
- Question “results” page – displays results for a particular question.
- Vote action – handles voting for a particular choice in a particular question.

In Django, web pages and other content are delivered by views.

Each view is represented by a simple Python function (or method, in the case of class-based views).

Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name).

Now in your time on the web you may have come across such beauties as `“ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B”`.

You will be pleased to know that Django allows us much more elegant URL patterns than that.

### Django 支援多元素的Url

A URL pattern is simply the general form of a URL - for example:

    /newsarchive/<year>/<month>/.

To get from a URL to a view, Django uses what are known as ‘URLconfs’. A URLconf maps URL patterns (described as regular expressions) to views.

This tutorial provides basic instruction in the use of URLconfs, and you can refer to [django.core.urlresolvers](https://docs.djangoproject.com/en/1.8/ref/urlresolvers/#module-django.core.urlresolvers) for more information.

## Write your first view

>>>> Goal:Create First View

polls/views.py

    from django.http import HttpResponse

    def index(request):
        return HttpResponse("Hello, world. You're at the polls index.")

Explanation :

>> To call the view, `we need to map it to a URL` - and for this we need a `URLconf`.

>> To create a `URLconf` in the polls directory, create a file called `urls.py`.

Your directory look like:

    polls/
        __init__.py
        admin.py
        models.py
        tests.py
        urls.py
        views.py

>> Create a file that call urls.py in polls app.

polls/urls.py

    from django.conf.urls import url

    from . import views

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

Next step

    1.Point the root URLconf at the `polls.urls` module.

    2.Include URLconf in mysite/urls.py

mysite/urls.py

    from django.conf.urls import include, url
    from django.contrib import admin

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

Try to run

    http://localhost:8000/polls/

You will get the message

    Hello, world. You’re at the polls index.

## url() function is passed four arguments

two required: `regex` and `view`,
and two optional: `kwargs`, and `name`.

### url() argument: regex

The term “regex” is a commonly used short form meaning “regular expression”, which is a syntax for matching patterns in strings, or in this case, url patterns. Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.

Note that these regular expressions do not search GET and POST parameters, or the domain name. For example, in a request to http://www.example.com/myapp/, the URLconf will look for myapp/. In a request to http://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.

If you need help with regular expressions, see Wikipedia’s entry and the documentation of the re module. Also, the O’Reilly book “Mastering Regular Expressions” by Jeffrey Friedl is fantastic. In practice, however, you don’t need to be an expert on regular expressions, as you really only need to know how to capture simple patterns. In fact, complex regexes can have poor lookup performance, so you probably shouldn’t rely on the full power of regexes.

Finally, a performance note: these regular expressions are compiled the first time the URLconf module is loaded. They’re super fast (as long as the lookups aren’t too complex as noted above).

### url() argument: view

When Django finds a regular expression match, Django calls the specified view function, with an HttpRequest object as the first argument and any “captured” values from the regular expression as other arguments. If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments. We’ll give an example of this in a bit.

### url() argument: kwargs

Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.

### url() argument: name

Naming your URL lets you refer to it unambiguously from elsewhere in Django especially templates. This powerful feature allows you to make global changes to the url patterns of your project while only touching a single file.

## Writing more views

Add more view in views.py

    def detail(request, question_id):
        return HttpResponse("You're looking at question %s." % question_id)

    def results(request, question_id):
        response = "You're looking at the results of question %s."
        return HttpResponse(response % question_id)

    def vote(request, question_id):
        return HttpResponse("You're voting on question %s." % question_id)

New View into polls/urls.py

>> Add More view to polls/view.py

polls/views.py

    def detail(request, question_id):
        return HttpResponse("You're looking at question %s." % question_id)

    def results(request, question_id):
        response = "You're looking at the results of question %s."
        return HttpResponse(response % question_id)

    def vote(request, question_id):
        return HttpResponse("You're voting on question %s." % question_id)

New views into the polls.urls module by adding the following url() calls:

    from django.conf.urls import url

    from . import views

    urlpatterns = [
        # ex: /polls/
        url(r'^$', views.index, name='index'),
        # ex: /polls/5/
        url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
        # ex: /polls/5/results/
        url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
        # ex: /polls/5/vote/
        url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    ]

try it

    /polls/34/          # it will run detail()

    /polls/34/results/  # it will run result()

    /polls/34/vote/     # it will run vote()

result in a call to the `detail` view like so :

    detail(request=<HttpRequest object>, question_id='34')

some thing like that

    url(r'^polls/latest\.html$', views.index),

don't do that.

## Write views that actually do something

>> Each view is responsible for doing one of two things:

- returning an `HttpResponse object` containing the content for the requested page,
- or `raising an exception` such as `Http404`.

Here’s one stab at a new index() view, which displays the latest 5 poll questions in the system, separated by commas, according to publication date:

polls/views.py

    from django.http import HttpResponse

    from .models import Question

    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        output = ', '.join([p.question_text for p in latest_question_list])
        return HttpResponse(output)

create a file in the polls/tempaltes/polls/index.html

polls/templates/polls/index.html

    {% if latest_question_list %}

        {% for question in latest_question_list %}

{{ question.question_text }}

        {% endfor %}

    {% else %}

No polls are available.

    {% endif %}

let’s update our index view in `polls/views.py` to use the template:

polls/views.py

    from django.http import HttpResponse
    from django.template import RequestContext, loader

    from .models import Question

    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        template = loader.get_template('polls/index.html')
        context = RequestContext(request, {
            'latest_question_list': latest_question_list,
        })
        return HttpResponse(template.render(context))

A shortcut : `render()`

    from django.shortcuts import render

    from .models import Question

    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        context = {'latest_question_list': latest_question_list}
        return render(request, 'polls/index.html', context)

`polls/index.html` is mean the file in `templates/polls/index.html`

## Raising a 404 error

polls/views.py

    from django.http import Http404
    from django.shortcuts import render

    from .models import Question
    # ...
    def detail(request, question_id):
        try:
            question = Question.objects.get(pk=question_id)
        except Question.DoesNotExist:
            raise Http404("Question does not exist")
        return render(request, 'polls/detail.html', {'question': question})

The new concept here: The view raises the Http404 exception if a question with the requested ID doesn’t exist.

polls/templates/polls/detail.html

    {{ question }}

A shortcut : get_object_or_404()

polls/views.py

    from django.shortcuts import get_object_or_404, render

    from .models import Question
    # ...
    def detail(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        return render(request, 'polls/detail.html', {'question': question})

## Use the template system

polls/detail.html

{{ question.question_text }}

    {% for choice in question.choice_set.all %}

{{ choice.choice_text }}

    {% endfor %}

## Removing hardcoded URLs in templates

polls/index.html

{{ question.question_text }}

this code hardcore the url.
using `{% url %}`

{{ question.question_text }}

It's

Replace to be

polls.urls.py

    # the 'name' value as called by the {% url %} template tag
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

replace to be

    # added the word 'specifics'
    url(r'^specifics/(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

## Namespacing URL names

mysite/urls.py

    from django.conf.urls import include, url
    from django.contrib import admin

    urlpatterns = [
        url(r'^polls/', include('polls.urls', namespace="polls")),
        url(r'^admin/', include(admin.site.urls)),
    ]

polls/index.html

{{ question.question_text }}

replace be

{{ question.question_text }}

# Part4

>> form processing and cutting down our code

Write a simple form.

polls/detail.html

{{ question.question_text }}

    {% if error_message %}
{{ error_message }}
{% endif %}

    <form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
        {{ choice.choice_text }}

    {% endfor %}
    <input type="submit" value="Vote" />
    </form>

polls/urls.py

    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),

polls/view.py

    from django.shortcuts import get_object_or_404, render
    from django.http import HttpResponseRedirect, HttpResponse
    from django.core.urlresolvers import reverse

    from .models import Choice, Question
    # ...
    def vote(request, question_id):
        p = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = p.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
            return render(request, 'polls/detail.html', {
                'question': p,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 1
            selected_choice.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

polls/view.py

    from django.shortcuts import get_object_or_404, render

    def results(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        return render(request, 'polls/results.html', {'question': question})

create `polls/results.html` in tempaltes

polls/results.html

{{ question.question_text }}

    {% for choice in question.choice_set.all %}

{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}

    {% endfor %}

    Vote again?

## Use generic views: Less code is better

### Amend URLconf

polls/urls.py

    from django.conf.urls import url

    from . import views

    urlpatterns = [
        url(r'^$', views.IndexView.as_view(), name='index'),
        url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
        url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
        url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    ]

### Amend views

polls/views.py

    from django.shortcuts import get_object_or_404, render
    from django.http import HttpResponseRedirect
    from django.core.urlresolvers import reverse
    from django.views import generic

    from .models import Choice, Question

    class IndexView(generic.ListView):
        template_name = 'polls/index.html'
        context_object_name = 'latest_question_list'

        def get_queryset(self):
            """Return the last five published questions."""
            return Question.objects.order_by('-pub_date')[:5]

    class DetailView(generic.DetailView):
        model = Question
        template_name = 'polls/detail.html'

    class ResultsView(generic.DetailView):
        model = Question
        template_name = 'polls/results.html'

    def vote(request, question_id):
    ... # same as above

url: https://raw.githubusercontent.com/williamHuang5468/QuicklyLearnDjango/feb98f91fe577bef59bfc112b8c0b3f56b2541ae/Wriating your first django app.md

path: /Wriating your first django app.md

filename: Wriating your first django app.md


text:
## 0.10.0

* Add support for Django 1.11 (#76 #78)

## 0.9.0

* Add support for all primary key formats (#75)
* Add support for Django 1.10 (#74)
* Remove support for Django 1.6 (#73)
* Documentation tweaks (#71 #70)

## 0.8.2

* Fix how the demo site stopped working because of bad settings

## 0.8.1

* Fix how extra_context set by admins was not passed
* Fix how if you had multiple admins, you always got redirected to the default admin

## 0.8.0

* Renames `objectactions` to `change_actions`
* Removes `get_object_actions` (see below)
* Adds `changelist_actions` for creating action tools in the change list view too
* Adds `get_change_actions` and `get_changelist_actions`

### Breaking changes

* Deleted `get_object_actions(request, context, **kwargs)`. If you used this
  before, use `get_change_actions(request, object_id, form_url)` instead. To
  get at the original object, instead of `context['original']`, you can use
  `self.model.get(pk=object_id)`, `self.get_object(request, object_id)`, etc.
  This isn't as convenient as it used to be, but now it uses the officially
  documented way to add extra context to admin views.
  https://docs.djangoproject.com/en/dev/ref/contrib/admin/#other-methods

* Renamed `objectactions`. In your admin, instead of defining your actions in
  the `objectactions` attribute, use `change_actions`.

repository: danmoz/django-object-actions

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: danmoz/django-object-actions


text:
# PIMPL macros

The header `PimplMacros.h` defines a few helper macros that allow us to write a correct PIMPL class in the blink of an eye, reducing the visual bloat of boilerplate code and letting the payload code outstand.

## Minimal usage

The minimal usage requires the macros:
+ `CMBASE64_DECLARE_PIMPL`
+ `CMBASE64_IMPLEMENT_PIMPL`

We would declare our PIMPL class in its header file (the `.h`) as follows:
```C++
class CMBASE64_API MyPimpl
{
    CMBASE64_DECLARE_PIMPL (MyPimpl)

public:
    // Interface functions...
};
```

Then, in the implementation file (the `.cpp`) we would write:
```C++
struct MyPimpl::Impl
{
    // Payload data...
};

CMBASE64_IMPLEMENT_PIMPL (MyPimpl)

// Implementation of interface functions
```

The struct `Impl` holds the actual payload. It must have that name and it has to be nested inside `MyPimpl`. The most important requirement is that it must be default-constructible.

You can put anything inside `MyPimpl::Impl`: a `std::vector`, a `std::string`, a `std::map` or some class of your own. This struct is only visible from inside this `.cpp` and is **not** part of the interface.

Then you would implement the interface functions of `MyPimpl`. These functions should receive or return only *safe* (ABI-stable) types: `int`, `double`, `char*`, `Span`, `ConstSpan`...

The interface functions of `MyPimpl` can use the member `pImpl` to access the `Impl` struct. Though, they must take into account that `pImpl` might be empty. Indeed, it will be empty right after construction. In that case, they must call `allocate()` or operate with some default value. Note that `allocate()` might throw exceptions.

Interface functions should never throw exceptions. Therefore, if they call `allocate()`, they should catch any possible exception and report it by means of some return value and/or the other member of the PIMPL class: `status`.

## Symmetric swap

The `_DECLARE_` and `_IMPLEMENT_` macros provide a `swap` member function, but it is also good to have a `swap` function outside of the class. The macro `CMBASE64_INLINE_SYMMETRIC_SWAP` helps providing that.

## Nested PIMPL classes

The macros also support the creation of nested (`_INNER_`) classes. Though, I discarded using them after a few experiments.

license: MIT


text:
---
aliases:
- zeal-offline-api-documentation-browser-for-linux
categories:
- Tools
date: "2014-06-15T23:14:00+05:30"
draft: false
slug: zeal-offline-api-documentation-browser-for-linux
tags:
- documentation
- linux
title: 'Zeal : Offline API documentation browser for Linux'
type: post
---
Quoted from zealdocs.org "Zeal is a simple offline API documentation browser inspired by [Dash](http://kapeli.com/dash) (OS X app), available Linux and Windows".

Zeal gives you offline API documentation for most of the Libraries out there like Angular, Backbone, Django and many more. You can check the list on Dash's [website](http://kapeli.com/dash#docsets)

You can easily install on Ubuntu 14.04 by following steps
##### Run following commands in terminal one by one
```
sudo add-apt-repository ppa:jerzy-kozera/zeal-ppa
sudo apt-get update
sudo apt-get install zeal
```

After installing Zeal it can be started from terminal by typing `zeal`. Add it to to Startup Application for quick access via hotkey which can be configured in `zeal` configurations.

#### Issues faced and Solutions

- I faced a minor issue after installing Zeal. I was not able to see main menu on top of it from where you can I found solution at [zeal issues](https://github.com/jkozera/zeal/issues/134) . I tried removing appmenu-qt5 package which worked from me.
- Every time starting Zeal will show a popup that it's Hotkey is confliting with system's. So I changed it's default Hotkey from Alt + Space to Ctrl + Shift + Space ([Synapse](http://kushdilip.com/blog/installing-synapse-launcher-in-ubuntu-14-04/) is already using Ctrl + Space)

repository: kushdilip/blog

gha_language: JavaScript

gha_license_id: MIT

repo_name: kushdilip/blog


text:
Torque3D
========

MIT Licensed Open Source version of [Torque 3D](http://www.garagegames.com/products/torque-3d) from [GarageGames](http://www.garagegames.com)

More Information
----------------

* Documentation is in the [Torque3D-Documentation](https://github.com/GarageGames/Torque3D-Documentation) GitHub repo.
* T3D [Beginner's Forum](http://www.garagegames.com/community/forums/73)
* T3D [Professional Forum](http://www.garagegames.com/community/forums/63)
* GarageGames [Professional Services](http://services.garagegames.com/)

License
-------

Copyright (c) 2012 GarageGames, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.


text:
## Using docker-compose to config startup environment

before we use docker compose, please install docker and docker-compose first : https://docs.docker.com/compose/install/

#### ShardingSphere-JDBC

1. access the docker folder (cd docker/shardingsphere-jdbc/sharding)
2. launch the environment by docker compose (docker-compose up -d)
3. access mysql / etcd / zookeeper as you want
4. if there is conflict on port, just modify the corresponding port defined in docker-compose.yml and then launch docker compose again(docker-compose up -d)
5. if you want to stop the environment, use command docker-compose down

#### ShardingSphere-Proxy

1. access the docker folder (cd docker/shardingsphere-proxy/sharding)
2. launch the environment by docker compose (docker-compose up -d)
3. access proxy by `psql -d sharding_db -h <IP_ADDRESS> -U root -p 3308 -W`, default password for example: root
4. if there is conflict on port, just modify the corresponding port defined in docker-compose.yml and then launch docker compose again(docker-compose up -d)
5. if you want to stop the environment, use command docker-compose down

to clean the docker container , you could use docker rm `docker ps -a -q` (be careful)

repository: apache/shardingsphere

gha_language: Java

repo_name: apache/shardingsphere


text:
# tailwind-datepicker
A basic date picker built with JS + Tailwind

## calendar.js
* Used by Year Calendar Laravel Module

## Inspired by
[Custom Date Picker in JavaScript & CSS](https://www.youtube.com/watch?v=wY2dao1hJms)

## Codepen Preview
[Codepen](https://codepen.io/webconxept/pen/povXVRg)

## Instructions
* Load the Javascript
* Insert the html datepicker code
* Create an input box with id="datepicker"
* Done!

repository: lewweiming/tailwind-datepicker

repo_name: lewweiming/tailwind-datepicker


text:
# Hackathon App

Welcome to the hackathon app: a web app using a React frontend and a python flask backend

### Getting setup for local development

#### Frontend

Node 10 is required for the frontend. You can use [nvm](https://github.com/creationix/nvm#installation) and [avn](https://github.com/wbyoung/avn#install) to easily switch Node versions between different projects.

```sh
cd frontend/
yarn install
yarn start
```
You can work on the frontend React app without running the python server or having any backend google sheets or looker instance dependencies. Simply skip the remaining setup.

#### Backend

hackathon_app requires python 3.7+ The easiest way to get this installed on a mac is to install [pyenv](https://github.com/pyenv/pyenv#installation) via [homebrew](https://brew.sh/)

```sh
brew install pyenv
```

**Important** [Follow these remaining steps (only 3 - 5)](https://github.com/pyenv/pyenv#basic-github-checkout) to complete the pyenv installation

Now you’re ready to install python 3.7 and set it as your global python version for the following steps

```sh
pyenv install 3.7.4
pyenv global 3.7.4
```

hackathon_app uses [pipenv](https://docs.pipenv.org/en/latest/#install-pipenv-today) to manage project dependencies

```sh
brew install pipenv
```

Install all dependencies.

```sh
pipenv install --dev
```

### Create a google spreadsheet

```sh
./create-test-sheet.sh<EMAIL_ADDRESS>```

Note the sheet ID (from the output) to use in the `env.list` file below.

### sheets api creds
Create a GCP project:
- enable Sheets api
- enable Drive api
- create a service account
- go back to your spreadsheet and "share" it with the email address of the service account

### Run local dev servers

Copy `env.list.sample` to `env.list` and modify accordingly

```sh
./start-dev-flask.sh
```

- this launches the backend server available at http://<IP_ADDRESS>:5000

```sh
cd frontend/
yarn start
```

- this launches the frontend static server at http://<IP_ADDRESS>:3000 which proxies fetch requests to the backend server

### Build docker image
Make sure to [install docker](https://download.docker.com/mac/stable/Docker.dmg)

```sh
./build-docker.sh
```

you can run the docker container locally with

```sh
./run-docker.sh
```

which exposes the whole app (both frontend and backend) on http://<IP_ADDRESS>:8080

to stop:

```sh
sh stop-docker.sh
```


text:
---
title: Removing EXIF Data Using Paint.net
date: 2011-02-22 00:00:00 +00:00
categories:
- How-To
tags:
- howto
- software
- tips
Date: 2011-02-22 13:55
Author: jamesleighton
Status: published
layout: post
image: "/images/Paint_NET_Logo.png"
redirect_from:
- "/2011/02/22/removing-exif-data-using-paint-net/"
---

A simple way to remove pesky EXIF data in photos (such as location information):

```Ctrl + A –> Ctrl + C –> Ctrl + Alt + V```

This copies the current image, and pastes it into a new file which you can simply save out minus the EXIF data.


text:
### ONLINE SHOP

### Done by
* Uwineza Nadine

### Description
The application will allow a user to The owner(Admin) to contol it and user to order his/her preffered product
### Technologies used
* django
* python3.8

### Set-up and Installation
* clone the repository
* Navigate to the directory you have cloned

### Running the application
* python3 manage.py runserver

### License
 MIT licence
 copyright(c) 2020 Uwineza Nadine

repository: nadineuwineza/ecommerce

repo_name: nadineuwineza/ecommerce


text:
{
  "title": "You can now use `tidy = \"styler\"` as an #rmarkdown chunk option to let styler prettify the printed #rstats code without having it touching the source. Needs #knitr devel version (https://t.co/cP7acEwOnm). Thanks @xieyihui. https://t.co/nuGXxsHZuR",
  "date": "2018-08-14"
}

# blogdown

> **rstatsUFV** (@RstatsUfv; 6/1): A snapshot of our R user group #rstats #rlang webpage (in production) using #blogdown @georgecushen academic @GoHugoIO theme, @github + @Netlify https://t.co/olRdSLr2XR  [↪](https://twitter.com/xieyihui/status/1029110450082996224)

<!-- -->

> **Mikaela Breunig** (@MikaelaBreunig; 3/0): Learning lots at R-Ladies Meetup tonight #git #versioncontrol #blogdown #UpSetPlots, and importantly- you can play pacman on R!! #Rcade  [↪](https://twitter.com/xieyihui/status/1029147768466669570)

<!-- -->

> **Azad AF** (@azadag; 0/0): @vgr Really true, but there have been a slew of new blogs in the data-science internet: 1. new tools (hugo/blogdown) have it easier to make good looking blogs to share portfolios / code 2. helps careers / binding self to 1. Was V1 blogging the same but for journalism?  [↪](https://twitter.com/xieyihui/status/1029024991805730822)

<!-- -->

# bookdown

> **Max Kuhn** (@topepos; 31/7): I love that the R/Pharma conference (https://t.co/CLzJTPzErf) is using shiny to register us for sessions (with a real time count for the number of seats remaining). The program website was made with #bookdown too. Eating our own dog food! #rstats  [↪](https://twitter.com/xieyihui/status/1029110418839621632)

<!-- -->

> **Yohan J. Rodríguez** (@hasdid; 1/1): #R | Write a Book with bookdown and Publish with Chapman & Hall https://t.co/i0GZ7UVQ67  [↪](https://twitter.com/xieyihui/status/1029058690878513154)

<!-- -->

> **Shawn Graham** (@electricarchaeo; 1/0): with over 20 jupyter notebooks (@ProjectJupyter) running via @mybinderteam and more than 120 pages of text (written w/ @rstudio and https://t.co/M4aZ59uQMt), and 10 contributors, #odate is going to be awesome! #digitalarchaeology #dh +  [↪](https://twitter.com/xieyihui/status/1029013570388865024)

<!-- -->

> **Nick Kelley** (@kelle569; 0/0): @EpiRen Thanks. Nice work on the data and explanations. Looking forward to seeing that bigger project. Are you familiar with https://t.co/FV5KdQTUVH  [↪](https://twitter.com/xieyihui/status/1028987867899547648)

<!-- -->

> **Brendan Knapp** (@knapply_; 0/0): @sometimes_data @znmeb Yes. https://t.co/YH9OQJ5BC4
>
Jupyter is cool, for sure, but I have yet to see them do anything Rmarkdown can’t do better.  [↪](https://twitter.com/xieyihui/status/1028875587165667328)

<!-- -->

# knitr

> **Lorenz Walthert** (@lorenzwalthert; 44/10): You can now use `tidy = "styler"` as an #rmarkdown chunk option to let styler prettify the printed #rstats code without having it touching the source. Needs #knitr devel version (https://t.co/cP7acEwOnm). Thanks @xieyihui. https://t.co/nuGXxsHZuR  [↪](https://twitter.com/xieyihui/status/1028974626100142080)

<!-- -->

> **Joyce Robbins** (@jtrnyc; 2/0): @alistaire Yes, it's here: https://t.co/5R9Bx180Vx (reusing chunks)  [↪](https://twitter.com/xieyihui/status/1028844408756752384)

<!-- -->

> **Edward Visel** (@alistaire; 2/0): @jtrnyc Is this like [child documents](https://t.co/OA2njdtYTV)? Is it documented somewhere?  [↪](https://twitter.com/xieyihui/status/1028842363131752448)

<!-- -->

> **Nathaniel Lane** (@straightedge; 1/0): @DogmaticPrior Took some phd ML that required R/knitr documents and it worked very well. The downsides were probably me not turning off warnings and all that mumbo jumbo. Seemed to also allow folks to assign hw using a template too. Probably made grading easier.  [↪](https://twitter.com/xieyihui/status/1029073042931175424)

<!-- -->

> **sometimes data** (@sometimes_data; 0/1): Rmarkdown and knitr is nice, but nothing beats executing individual code chunks and seeing the output rendered complete. Jupyter is WYSIWYG! #rstats #Jupyter  [↪](https://twitter.com/xieyihui/status/1028863515996483584)

<!-- -->

> **Garrick Aden-Buie** (@grrrck; 0/0): @EvaMaeRey Cool! Thanks for sharing! I've been meaning to write up a little blog highlighting the code+plot side-by-side, but for the curious you use a second knitr chunk with `ref.label = "code_chunk"` to put the plot in the right col (referencing the code chunk in left col).  [↪](https://twitter.com/xieyihui/status/1029166949379567616)

<!-- -->

> **ワープ** (@ns_and_5up; 0/0): @n_knitr
そろそろお譲りに関しての話を詰めたいのですが、一向に連絡が取れないため困惑しています。
フォロー承認のお返事もありませんし…。
明日（15日）の朝8時半までにご連絡がない場合、勝手ながら今回のお取引はなかったことにさせていただきます。
お早いご連絡お待ち申し上げます。  [↪](https://twitter.com/xieyihui/status/1029147409266368512)

<!-- -->

> **ワープ** (@ns_and_5up; 0/0): @n_knitr
あれ以降お返事がありませんが、何が問題でも起きましたでしょうか？
フォローのご返答がまだなので、DMも送れず困っております。  [↪](https://twitter.com/xieyihui/status/1028855045150797825)

<!-- -->

> **Kyle Cranmer** (@KyleCranmer; 0/0): @albz_marocchino @jonathansick @LSST @ProjectJupyter Isn’t that basically what Jupiter notebooks are trying to do?
there are also things like knitr
https://t.co/sZqqCSzAht  [↪](https://twitter.com/xieyihui/status/1029127594896252928)

<!-- -->

# xaringan

> **Gina Reynolds** (@EvaMaeRey; 3/0): Learning and borrowing from @grrrck's excellent Xaringan materials to show code and plot side-by-side!  https://t.co/D7MhYVvvvU  [↪](https://twitter.com/xieyihui/status/1029106141811404800)

<!-- -->

> **Kirill Müller** (@krlmlr; 2/0): @BrodieGaslam Awesome! Works as advertised also in a xaringan deck (why shouldn't it... 🙃), just in time 🥳  [↪](https://twitter.com/xieyihui/status/1029126760703635461)

<!-- -->

# yihui.name

> **Joyce Robbins** (@jtrnyc; 2/0): @alistaire Yes, it's here: https://t.co/5R9Bx180Vx (reusing chunks)  [↪](https://twitter.com/xieyihui/status/1028844408756752384)

<!-- -->

> **Edward Visel** (@alistaire; 2/0): @jtrnyc Is this like [child documents](https://t.co/OA2njdtYTV)? Is it documented somewhere?  [↪](https://twitter.com/xieyihui/status/1028842363131752448)

<!-- -->

> **Yohan J. Rodríguez** (@hasdid; 1/1): #R | Double Negatives https://t.co/dEr5q0RPfv  [↪](https://twitter.com/xieyihui/status/1029058717461954561)

<!-- -->

> **Yohan J. Rodríguez** (@hasdid; 1/1): #R | Reflections on 25+ Years of “50 Years of Data Science” https://t.co/ocheiY76VQ  [↪](https://twitter.com/xieyihui/status/1029058692493307904)

<!-- -->

> **Yohan J. Rodríguez** (@hasdid; 1/1): #R | Write a Book with bookdown and Publish with Chapman & Hall https://t.co/i0GZ7UVQ67  [↪](https://twitter.com/xieyihui/status/1029058690878513154)

<!-- -->

> **Kyle Cranmer** (@KyleCranmer; 0/0): @albz_marocchino @jonathansick @LSST @ProjectJupyter Isn’t that basically what Jupiter notebooks are trying to do?
there are also things like knitr
https://t.co/sZqqCSzAht  [↪](https://twitter.com/xieyihui/status/1029127594896252928)

<!-- -->

repository: cgpu/twitter-blogdown

repo_name: cgpu/twitter-blogdown


text:
---
title: Installation
---

Administration »

« Structure

- [Installation](#installation)
  - [Server Requirements](#server-requirements)
  - [1. Clone the Github Repo](#1-clone-the-github-repo)
  - [2. Create your `.env` Files](#2-create-your-env-files)
  - [3. Blockchain Setup](#3-blockchain-setup)
    - [Setting Up A Provider](#setting-up-a-provider)
    - [Using a Custom Infura Account](#using-a-custom-infura-account)
    - [Setting Up Your Wallet](#setting-up-your-wallet)
      - [A Note About Your Wallet's Balance](#a-note-about-your-wallets-balance)
      - [Metamask](#metamask)
      - [Testnet Faucets](#testnet-faucets)
    - [Deploying Your Contract](#deploying-your-contract)
      - [Update your `.env` file](#update-your-env-file)
      - [Run the Deploy Command](#run-the-deploy-command)
  - [4. Configuration Setup](#4-configuration-setup)
    - [Update Your `.env` Files](#update-your-env-files)
    - [Configuring Data Source Credentials](#configuring-data-source-credentials)
      - [Qualtrics](#qualtrics)
    - [A Note About Deploying to PaaS Services (Config Values)](#a-note-about-deploying-to-paas-services-config-values)
  - [5. Deploying](#5-deploying)
    - [Docker](#docker)
    - [Manually Building and Deploying](#manually-building-and-deploying)
      - [Postgres](#postgres)
      - [Frontend](#frontend)
        - [Install Dependencies](#install-dependencies)
        - [Create a Build](#create-a-build)
      - [API](#api)
        - [Install Dependencies](#install-dependencies-1)
        - [Create a Build](#create-a-build-1)
    - [Heroku Example](#heroku-example)

# Installation

## Server Requirements

- [NodeJS 10.16+](https://nodejs.org/en/download/)
- [Postgres 12.2+](https://www.postgresql.org/download/)

## 1. Clone the Github Repo

The GitHub repo for the project can be found here. You'll need to clone this locally before you begin.

To do this, use a CLI tool (for example "Terminal" on Mac), navigate to the directory where you want the project to live (`cd path/to/survey_assure`), and close the repo using:

```
git clone https://github.com/newamericafoundation/digi_survey_assure.git .
```

If your machine doesn't have git installed, please refer to this documentation.

## 2. Create your `.env` Files

In both `/api` and `/frontend`, make a copy of `.example.env` and rename them to `.env`. You will be editing these throughout the setup process.

## 3. Blockchain Setup

### Setting Up A Provider

The application uses [EtherJS](https://docs.ethers.io/ethers.js/html/) for all interactions with the Blockchain. EtherJS comes with a default provider that connects to both Etherscan & Infura simultaneously, thereby negating the need for you to run a node. In most cases, we recommend that you use this provider, however if you want to set up your own provider you are welcome to do so.

### Using a Custom Infura Account

While not required, if you choose to set up your own [Infura](https://infura.io/) account, you can do so from their website and then update the following config options on your `api/.env` file before deploying your contract:

```
INFURA_PROJECT_ID
INFURA_PROJECT_SECRET
```

Creating your own Infura account gives you the added benefit of statistics around your calls to the Blockchain.

### Setting Up Your Wallet

In order to properly utilize the Blockchain for survey responses, you will need to be able to fund transactions. As such, you will need to provide the application with a private key for a wallet you own. We recommend creating a dedicated wallet using [Metamask](https://metamask.io/) for this task. Please see their documentation for information on how to export your key once you've created a wallet.

Once exported, open the `api/.env` file and update this config value:

```
BLOCKCHAIN_WALLET_PRIVATE_KEY
```

#### A Note About Your Wallet's Balance

You will need to manually manage your wallet and ensure that it always has an acceptable balance (Survey Assure does not do this for you). Failure to do so will result in rejected Blockchain requests. Please see the "Estimating Blockchain Costs" section for a general guide on anticipated costs.

#### Metamask

Metamask provides extensions for various web browsers, such as Chrome. [Download](https://metamask.io/download.html) and install Metamask in your browser of choice.

Once installed, you will need to fund your wallet. To fund your wallet, you can use a faucet (if you are using a Testnet) or you can send ETH from another source to your Metamask wallet (if you are using the Mainnet).

**If you are using the Ethereum Mainnet and need to purchase ETH, please ensure that you only purchase ETH from [reputable sources](https://docs.ethhub.io/using-ethereum/how-to-buy-ether/).** Refer to the "Estimating Blockchain Costs" below for more information on expected costs.

#### Testnet Faucets

Faucets allow you to acquire a small amount of "testnet ETH". [Click here](https://docs.ethhub.io/using-ethereum/test-networks/) for information on the differences between the various testnets. Recommended Ethereum Testnets:

- [Kovan](https://faucet.kovan.network/)
- [Rinkeby](https://www.rinkeby.io/#faucet)
- [Ropsten](https://faucet.ropsten.be/)

Others exist but will need to be integrated with Infura to work out-of-the-box with the platform. If you choose to integrate directly with your custom node, you will need to create a [JsonRpcProvider](https://docs.ethers.io/ethers.js/html/api-providers.html) from within the `api/src/service/blockchainService.ts` service.

### Deploying Your Contract

#### Update your `.env` file

Now that you have selected a network to deploy on and have found your private key in Metamask, you will need to open your `api/.env` file and update the following config value:

- `BLOCKCHAIN_PROVIDER_NETWORK`: Set this to the name of your desired network.

#### Run the Deploy Command

**Important Note:** You can choose to deploy from your local computer, or you can choose to push your project to your hosting provider and deploy from there. If you choose to deploy locally, make sure you run `npm install` and `npm run build` from the `api` directory.

To deploy your contract, you will need to run the following command using a command line tool running from the `api` folder within the project:
- `npm run bc:deploy`

You should see something like the following on your screen once successful:

```
--- Your Contact Address ---> YOUR_CONTRACT_ADDRESS_HERE
--- Your transaction hash ---> YOUR_TX_ID_HERE
```

Copy the value of `YOUR_CONTRACT_ADDRESS_HERE` into your `api/.env` file under the `BLOCKCHAIN_CONTRACT_ADDRESS` config option.

You are now ready to deploy the application to your web server. If the application throws an error, you will need to double check all of your Blockchain config values to ensure that they are correct and try again.

## 4. Configuration Setup

### Update Your `.env` Files

Open your new `.env` file and update your environment variables according to your desired configuration (follow the comments within each `.env` file for information on what each config value represents.).

**Important: Never commit the `.env` file to a git repository and keep its contents secret at all times!**

You will need to edit two `.env` files:
- `frontend/.env`
- `api/.env`

### Configuring Data Source Credentials

The application reserves five config variables for integrating with various data sources. Please see this guide on which you will need to update for each provider:

#### Qualtrics

```
SURVEY_DATA_PROVIDER_URL=https://DATACENTER_ID_HERE.qualtrics.com/API/v3
SURVEY_DATA_PROVIDER_CRED1=YOUR_API_KEY_HERE
```

- [Locating your data center ID](https://api.qualtrics.com/docs/base-url-and-datacenter-ids)
- [Locating your API key](https://api.qualtrics.com/docs/api-key-authentication)

### A Note About Deploying to PaaS Services (Config Values)

If you are deploying to a PaaS platform like [Heroku](https://devcenter.heroku.com/articles/config-vars), [Netlify](https://docs.netlify.com/configure-builds/environment-variables/) or [AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html#environments-cfg-softwaresettings-console) without using Docker, you will need to manually input all environment variables into those platforms directly before deploying. In other words, your `.env` file only matters for Docker and local deployments.

## 5. Deploying

A number of options are available to you when it comes to deploying the application. Please select the strategy which best fits your business needs.

### Docker

The tool comes with Docker Compose, allowing you to build all needed components automatically. Run `docker-compose up` to build the images and launch the app. Please see the `docker-compose.yml` file for information on ports, etc.. By default the app is exposed on port 4000 (`http://localhost:4000`).

If you choose to use Docker, please see your respective cloud service for information on deploying Docker-based applications.

### Manually Building and Deploying

The app is effectively two apps in one: a Koa-based API and a ReactJS-based frontend. When manually deploying (or developing locally), you will need to build and deploy both.

#### Postgres

You will need [Postgres](https://www.postgresql.org/) running locally before the application will work. Postgres is free and open source.

Once running, create a database that the application can use. An example (which is actually used by Docker for the production build) can be found within the `api/db/init.sql` file.

Once your database is set up, update your `api/.env` file with the correct connection details.

```
PGDATABASE
PGHOST
PGPASSWORD
PGPORT
PGUSER
````

#### Frontend

The frontend uses [React Create App](https://github.com/facebook/create-react-app); please see their documentation for a more in-depth guide.

##### Install Dependencies

- Before building, run `npm install`.

##### Create a Build

- Production build: `npm run build`
  - Development build (real-time rebuilds): `npm start`

Once you run the production build command, your app will be automatically served as a static route from the API. AFTER building and starting the API, simply point your browser to the designated port within the API's config (defaults to 4000) to see your app in action (`http://localhost:4000/`).

#### API

##### Install Dependencies

- Before building, run `npm install`.

### Heroku Example

The following example is not an endorsement of Heroku over other platforms, but rather a practical example of the above steps for a real-world platform. The process would be *very* similar for other PaaS providers.

- In Heroku, create two separate apps, one for the API (buildpack = heroku/nodejs), one for the frontend (buildpack = https://github.com/mars/create-react-app-buildpack).
- For the API, provision a "Heroku Postgres" add-on.
- For both apps, copy the contents of the respective local `.env` files to the respective Heroku app configs under "Settings > Reveal Config Vars" in Heroku. Make changes as necessary, keeping in mind that Heroku will automatically set `DATABASE_URL` for you once the database is provisioned, so you should not manually add it. Also note that you will need to use `DATABASE_USE_SSL=true` to connect to Heroku Postgres.
- For both the frontend and API, follow the instructions provided within Heroku under "Deploy > Deploy using Heroku Git" to push your code to Heroku.
- You should now be live!

Administration »

« Structure


text:
---
title: Automatic Saving Of Invalid Resources in Rails While Maintaining a Clean RESTful Interface
permalink: 2008/06/09/automatic-saving-of-invalid-resources-in-rails-while-maintaining-a-clean-restful-interface
published_at: 2008-06-09 13:35:00 +0000
---

or, **How To Change Your World In One Line Of Code**

One of the cool things that we're doing at the AMC is building a large collection of loosely coupled Rails applications that communicate using REST. This is slightly unusual, as rails is predominantly used to build single apps that operate in isolation. In our experiences, we've picked up a number of tricks that we'd like to share. Here's the first, on how a single this single line of code has saved us weeks of time and effort. Here's the line in question:

```
if @bank_transaction.save && @bank_transaction.valid?
```

Read on to find out how this helps!

## RESTful Resources

This line is part of a new Rails app we're developing to centrally handle all online payments for our software systems at the AMC. In this payments application, we expose two key resources over REST: (1) line items, which the other apps create with the details of the items to purchase, and (2) bank transactions, which are passed line item IDs and credit card details for the purchase.

Naturally, the models behind these resources have a bunch of validation rules that ensure certain conditions are met before they can be saved successfully. If any of these requirements are not met, then the model fails to save and the error hash is returned to the client app.

For most resources, these error hashes are returned in the usual Rails-like way. Let's look at how `LineItemsController` does it:

```
class LineItemsController < ApplicationController
  # POST /line_items.xml
  def create
    @line_item = LineItem.new params[:line_item]
    respond_to do |format|
      if @line_item.save
        format.xml { render :xml => @line_item, :status => :created, :location => @line_item }
      else
        format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity }
      end
    end
  end
end
```

To paraphrase: if the items save successfully, return success and the line item in XML, otherwise return the error hash. Nice and predictable, nothing exciting here.

## Saving Invalid Resources

One of the resources in the payments app is different. These are the @BankTransactions@, which are about as "mission critical" as we get. Let's talk about the successful case first: during the creation of the `BankTransaction` model, if all the validations have passed, a before\_create callback is triggered that will talk to the bank (using ActiveMerchant, of course) and ask to make the transaction there. If this succeeds, the model is saved to the database and an XML representation of the saved model is passed back to the client application with a success code.

However, if the transaction with the bank fails, this is still information we care about. A failed transaction could be an indication of a larger problem, and also needs to be recorded for customer service purposes. It makes sense to save every failed transaction as well as every successful one. To this end, the callback that communicates with the bank always returns true, which allows the save continue, and records for both successful and unsuccessful transactions to be kept in the database.

_(Another approach to this problem would be to create a separate @TransactionLog@ model to store the transaction data, but this approach requires extra work. Having the `BankTransactions` save every time is essentially free. Excellent.)_

## Keeping the REST API Simple

While the payments app is saving unsuccessful transactions, the client apps do not want to keep these records around: all they care about is if a transaction is successful or not. The easiest way to make it simple for the clients is to make the creation of a bank transaction resource behave the same way as creating any other resource over REST in rails. This means that if a transaction with the bank fails, then it should _appear_ to the clients as if the save also failed.

This will require the controller to generate an errors hash if the transaction fails. This means that the model should be invalid at this point. Given that we save to the database even for failed transactions, the model should therefore be invalid after the save:

```
class BankTransaction < ActiveRecord::Base
  validate :must_be_successful_if_saved
  before_create :transact

  private

  def transact
    # talk to the bank here, and set self.success to true or false pending the results
    # return true to make sure a save always occurs
    true
  end

  def must_be_successful_if_saved
    errors.add_to_base("failed to transact successfully with the bank") if !new_record? && !success?
  end
end
```

And then, in the `BankTransactionsController`, that one magic line:

```
class BankTransactionsController < ApplicationController
  # POST /bank_transactions.xml
  def create
    @bank_transaction = BankTransaction.new params[:bank_transaction]
    respond_to do |format|
      if @bank_transaction.save && @bank_transaction.valid?
        format.xml { render :xml => @bank_transaction, :status => :created, :location => @bank_transaction }
      else
        format.xml { render :xml => @bank_transaction.errors, :status => :unprocessable_entity }
      end
    end
  end
end
```

Unlike the standard behaviour shown in the `LineItemsController` above, we only return a successfully created model if the save is successful AND it is still valid afterwards. A saved model for a failed transaction with the bank will be invalid at this point, so it will return the errors hash. To the client app, this looks like the same resource it tried to create initially, and so it can proceed as usual to display the errors, ask for corrections if necessary, and try to save again. In the background, the payments app has saved every failed transaction for safe keeping.

repository: timriley/my-site

gha_language: Ruby

repo_name: timriley/my-site


text:
# Reference
<!-- DO NOT EDIT: This document was generated by Puppet Strings -->

## Table of Contents

**Functions**

* [`extlib::cache_data`](#extlibcache_data): Retrieves data from a cache file, or creates it with supplied data if the file doesn't exist
* [`extlib::default_content`](#extlibdefault_content): Takes an optional content and an optional template name and returns the contents of a file.
* [`extlib::dump_args`](#extlibdump_args): Prints the args to STDOUT in Pretty JSON format.
* [`extlib::echo`](#extlibecho): This function outputs the variable content and its type to the debug log. It's similiar to the `notice` function but provides a better output
* [`extlib::has_module`](#extlibhas_module): A function that lets you know whether a specific module is on your modulepath.
* [`extlib::ip_to_cron`](#extlibip_to_cron): Provides a "random" value to cron based on the last bit of the machine IP address. used to avoid starting a certain cron job at the same time
* [`extlib::random_password`](#extlibrandom_password): A function to return a string of arbitrary length that contains randomly selected characters.
* [`extlib::resources_deep_merge`](#extlibresources_deep_merge): Deeply merge a "defaults" hash into a "resources" hash like the ones expected by `create_resources()`.
* [`extlib::sort_by_version`](#extlibsort_by_version): A function that sorts an array of version numbers.

## Functions

### extlib::cache_data

Type: Ruby 4.x API

Retrieves data from a cache file, or creates it with supplied data if the
file doesn't exist

Useful for having data that's randomly generated once on the master side
(e.g. a password), but then stays the same on subsequent runs. Because it's
stored on the master on disk, it doesn't work when you use mulitple Puppet
masters that don't share their vardir.

#### `extlib::cache_data(String[1] $namespace, String[1] $name, Any $initial_data)`

Retrieves data from a cache file, or creates it with supplied data if the
file doesn't exist

Useful for having data that's randomly generated once on the master side
(e.g. a password), but then stays the same on subsequent runs. Because it's
stored on the master on disk, it doesn't work when you use mulitple Puppet
masters that don't share their vardir.

Returns: `Any` The cached value when it exists. The initial data when no cache exists

##### `namespace`

Data type: `String[1]`

Namespace for the cache

##### `name`

Data type: `String[1]`

Cache key within the namespace

##### `initial_data`

Data type: `Any`

The data for when there is no cache yet

### extlib::default_content

Type: Ruby 4.x API

Takes an optional content and an optional template name and returns the contents of a file.

#### `extlib::default_content(Optional[String] $content, Optional[String] $template_name)`

Takes an optional content and an optional template name and returns the contents of a file.

Returns: `Optional[String]` Returns the value of the content parameter if it's a non empty string.
Otherwise returns the rendered output from `template_name`.
Returns `undef` if both `content` and `template_name` are `undef`.

##### `content`

Data type: `Optional[String]`

##### `template_name`

Data type: `Optional[String]`

The path to an .erb or .epp template file or `undef`.

### extlib::dump_args

Type: Ruby 4.x API

Prints the args to STDOUT in Pretty JSON format.

Useful for debugging purposes only. Ideally you would use this in
conjunction with a rspec-puppet unit test.  Otherwise the output will
be shown during a puppet run when verbose/debug options are enabled.

#### `extlib::dump_args(Any $args)`

Prints the args to STDOUT in Pretty JSON format.

Useful for debugging purposes only. Ideally you would use this in
conjunction with a rspec-puppet unit test.  Otherwise the output will
be shown during a puppet run when verbose/debug options are enabled.

Returns: `Undef` Returns nothing.

##### `args`

Data type: `Any`

The data you want to dump as pretty JSON.

### extlib::echo

Type: Ruby 4.x API

This function outputs the variable content and its type to the
debug log. It's similiar to the `notice` function but provides
a better output format useful to trace variable types and values
in the manifests.

```
$v1 = 'test'
$v2 = ["1", "2", "3"]
$v3 = {"a"=>"1", "b"=>"2"}
$v4 = true
# $v5 is not defined
$v6 = { "b" => { "b" => [1,2,3], "c" => true, "d" => { 'x' => 'y' }}, 'x' => 'y', 'z' => [1,2,3,4,5,6]}
$v7 = 12345

echo($v1, 'My string')
echo($v2, 'My array')
echo($v3, 'My hash')
echo($v4, 'My boolean')
echo($v5, 'My undef')
echo($v6, 'My structure')
echo($v7) # no comment here
debug log output
My string (String) "test"
My array (Array) ["1", "2", "3"]
My hash (Hash) {"a"=>"1", "b"=>"2"}
My boolean (TrueClass) true
My undef (String) ""
My structure (Hash) {"b"=>{"b"=>["1", "2", "3"], "c"=>true, "d"=>{"x"=>"y"}}, "x"=>"y", "z"=>["1", "2", "3", "4", "5", "6"]}
(String) "12345"
```

#### `extlib::echo(Any $value, Optional[String] $comment)`

This function outputs the variable content and its type to the
debug log. It's similiar to the `notice` function but provides
a better output format useful to trace variable types and values
in the manifests.

```
$v1 = 'test'
$v2 = ["1", "2", "3"]
$v3 = {"a"=>"1", "b"=>"2"}
$v4 = true
# $v5 is not defined
$v6 = { "b" => { "b" => [1,2,3], "c" => true, "d" => { 'x' => 'y' }}, 'x' => 'y', 'z' => [1,2,3,4,5,6]}
$v7 = 12345

echo($v1, 'My string')
echo($v2, 'My array')
echo($v3, 'My hash')
echo($v4, 'My boolean')
echo($v5, 'My undef')
echo($v6, 'My structure')
echo($v7) # no comment here
debug log output
My string (String) "test"
My array (Array) ["1", "2", "3"]
My hash (Hash) {"a"=>"1", "b"=>"2"}
My boolean (TrueClass) true
My undef (String) ""
My structure (Hash) {"b"=>{"b"=>["1", "2", "3"], "c"=>true, "d"=>{"x"=>"y"}}, "x"=>"y", "z"=>["1", "2", "3", "4", "5", "6"]}
(String) "12345"
```

Returns: `Undef` Returns nothing.

##### `value`

Data type: `Any`

The value you want to inspect.

##### `comment`

Data type: `Optional[String]`

An optional comment to prepend to the debug output.

### extlib::has_module

Type: Ruby 4.x API

A function that lets you know whether a specific module is on your modulepath.

#### `extlib::has_module(Pattern[/\A\w+[-\/]\w+\z/] $module_name)`

A function that lets you know whether a specific module is on your modulepath.

Returns: `Boolean` Returns `true` or `false`.

##### `module_name`

Data type: `Pattern[/\A\w+[-\/]\w+\z/]`

The full name of the module you want to know exists or not.
Namespace and modulename can be separated with either `-` or `/`.

### extlib::ip_to_cron

Type: Ruby 4.x API

Provides a "random" value to cron based on the last bit of the machine IP address.
used to avoid starting a certain cron job at the same time on all servers.
Takes the runinterval in seconds as parameter and returns an array of [hour, minute]

example usage
```
ip_to_cron(3600) - returns [ '*', one value between 0..59 ]
ip_to_cron(1800) - returns [ '*', an array of two values between 0..59 ]
ip_to_cron(7200) - returns [ an array of twelve values between 0..23, one value between 0..59 ]
```

#### `extlib::ip_to_cron(Optional[Integer[1]] $runinterval)`

Provides a "random" value to cron based on the last bit of the machine IP address.
used to avoid starting a certain cron job at the same time on all servers.
Takes the runinterval in seconds as parameter and returns an array of [hour, minute]

example usage
```
ip_to_cron(3600) - returns [ '*', one value between 0..59 ]
ip_to_cron(1800) - returns [ '*', an array of two values between 0..59 ]
ip_to_cron(7200) - returns [ an array of twelve values between 0..23, one value between 0..59 ]
```

Returns: `Array`

##### `runinterval`

Data type: `Optional[Integer[1]]`

The number of seconds to use as the run interval

### extlib::random_password

Type: Ruby 4.x API

A function to return a string of arbitrary length that contains randomly selected characters.

#### `extlib::random_password(Integer[1] $length)`

A function to return a string of arbitrary length that contains randomly selected characters.

Returns: `String` The random string returned consists of alphanumeric characters excluding 'look-alike' characters.

##### `length`

Data type: `Integer[1]`

The length of random password you want generated.

### extlib::resources_deep_merge

Type: Ruby 4.x API

Deeply merge a "defaults" hash into a "resources" hash like the ones expected by `create_resources()`.

Internally calls the puppetlabs-stdlib function `deep_merge()`. In case of
duplicate keys the `resources` hash keys win over the `defaults` hash keys.

Example
```puppet
$defaults_hash = {
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
  'four'  => {
    'five'  => '5',
    'six'   => '6',
    'seven' => '7',
  }
}

$numbers_hash = {
  'german' => {
    'one'   => 'eins',
    'three' => 'drei',
    'four'  => {
      'six' => 'sechs',
    },
  },
  'french' => {
    'one' => 'un',
    'two' => 'deux',
    'four' => {
      'five'  => 'cinq',
      'seven' => 'sept',
    },
  }
}

$result_hash = resources_deep_merge($numbers_hash, $defaults_hash)
```

The $result_hash then looks like this:

```puppet
$result_hash = {
  'german' => {
    'one'   => 'eins',
    'two'   => '2',
    'three' => 'drei',
    'four'  => {
      'five'  => '5',
      'six'   => 'sechs',
      'seven' => '7',
    }
  },
  'french' => {
    'one'   => 'un',
    'two'   => 'deux',
    'three' => '3',
    'four'  => {
      'five'  => 'cinq',
      'six'   => '6',
      'seven' => 'sept',
    }
  }
}
```

#### `extlib::resources_deep_merge(Hash $resources, Hash $defaults)`

Deeply merge a "defaults" hash into a "resources" hash like the ones expected by `create_resources()`.

Internally calls the puppetlabs-stdlib function `deep_merge()`. In case of
duplicate keys the `resources` hash keys win over the `defaults` hash keys.

Example
```puppet
$defaults_hash = {
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
  'four'  => {
    'five'  => '5',
    'six'   => '6',
    'seven' => '7',
  }
}

$numbers_hash = {
  'german' => {
    'one'   => 'eins',
    'three' => 'drei',
    'four'  => {
      'six' => 'sechs',
    },
  },
  'french' => {
    'one' => 'un',
    'two' => 'deux',
    'four' => {
      'five'  => 'cinq',
      'seven' => 'sept',
    },
  }
}

$result_hash = resources_deep_merge($numbers_hash, $defaults_hash)
```

The $result_hash then looks like this:

```puppet
$result_hash = {
  'german' => {
    'one'   => 'eins',
    'two'   => '2',
    'three' => 'drei',
    'four'  => {
      'five'  => '5',
      'six'   => 'sechs',
      'seven' => '7',
    }
  },
  'french' => {
    'one'   => 'un',
    'two'   => 'deux',
    'three' => '3',
    'four'  => {
      'five'  => 'cinq',
      'six'   => '6',
      'seven' => 'sept',
    }
  }
}
```

Returns: `Hash` Returns the merged hash.

##### `resources`

Data type: `Hash`

The hash of resources.

##### `defaults`

Data type: `Hash`

The hash of defaults to merge.

### extlib::sort_by_version

Type: Ruby 4.x API

A function that sorts an array of version numbers.

#### `extlib::sort_by_version(Array[String] $versions)`

A function that sorts an array of version numbers.

Returns: `Array[String]` Returns the sorted array.

##### `versions`

Data type: `Array[String]`

An array of version strings you want sorted.

repository: Phil-Friderici/puppet-extlib

repo_name: Phil-Friderici/puppet-extlib


text:
Leaflet Routing Machine / OpenRoute Service
===========================================

NOTE: As of the latest commit, this is a preliminary implementation. For example, there is NO Browserfy implementation at this time, as is the norm for other extentions of the Leaflet Routing Machine.

Author: [James G. Willmore](mailto:willmorejg@gmail.com?subject=lrm-openrouteservice%20inquiry)

License: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0)

Extends [Leaflet Routing Machine](https://github.com/perliedman/leaflet-routing-machine) with support for [OpenRoute Service](https://go.openrouteservice.org/) routing API.

Some brief instructions follow below, but the [Leaflet Routing Machine tutorial on alternative routers](http://www.liedman.net/leaflet-routing-machine/tutorials/alternative-routers/) is recommended.

## Installing

Put the script [L.Routing.OpenRouteService.js](lrm-openrouteservice/L.Routing.OpenRouteService.js) after Leaflet and Leaflet Routing Machine has been loaded.

## Using

There's a single class exported by this module, `L.Routing.OpenRouteService`. It implements the [`IRouter`](http://www.liedman.net/leaflet-routing-machine/api/#irouter) interface. Use it to replace Leaflet Routing Machine's default OSRM router implementation:

```javascript
L.Routing.control({
    router: new L.Routing.openrouteservice('api key'),
}).addTo(map);
```

```javascript
L.Routing.control({
    router: new L.Routing.openrouteserviceV2(
        '{{ openserviceroute_key }}',
        {
                profile: "driving-car",
                geometry_simplify: true // Needs to do _decodePolyline and smaller request
        }
    ),
}).addTo(map);
```

Note that you will need to pass a valid OpenRoute Service api key and options to the constructor.

repository: boswellp/lrm-openrouteservice

repo_name: boswellp/lrm-openrouteservice


text:
# Unsupervised Learning Of Dense Shape Correspondence
### Computer Vision and Pattern Recognition (CVPR), 2019 - Oral presentation
**Authors: Oshri Halimi, [Or Litany](https://orlitany.github.io), [Emanuele Rodola](https://sites.google.com/site/erodola/), Alex Bronstein, Ron Kimmel**

[Paper](http://openaccess.thecvf.com/content_CVPR_2019/html/Halimi_Unsupervised_Learning_of_Dense_Shape_Correspondence_CVPR_2019_paper.html) / [Video](https://www.youtube.com/watch?v=OPKRc6uQrNg&t=155s)

![](https://github.com/OshriHalimi/unsupervised_learning_of_dense_shape_correspondence/blob/master/Picture1.png)

**If you use this code, please cite the paper.**
```
@inproceedings{halimi2019unsupervised,
  title={Unsupervised Learning of Dense Shape Correspondence},
  author={Halimi, Oshri and Litany, Or and Rodola, Emanuele and Bronstein, Alex M and Kimmel, Ron},
  booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
  pages={4370--4379},
  year={2019}
}
```

### LICENSE.txt
**Important Note:**
The license is granted only for the code and not for the data. The data we used belongs to MPI-Faust project and the preprocessed models are available here only to make the paper reproduction more easy.

## Getting Started
This tutorial will guide you how to run the experiments that appear in the paper **"Unsupervised Learning Of Dense Shape Correspondence" (CVPR 2019)**. The reader might be also interested in the supervised algorithm **"Deep Functional Maps:
Structured Prediction for Dense Shape Correspondence" (ICCV 2017)** [paper](http://vision.in.tum.de/_media/spezial/bib/litany-iccv17.pdf)/[code](https://github.com/orlitany/DeepFunctionalMaps).

### Code organization
Each folder contains the code and data for a specific experiment.
The repository is still updating, and I intend to finish organizing and uploading the whole code very soon :)
### Contact Information
For any questions regarding the code/paper, please contact<EMAIL_ADDRESS>
## Single Pair Experiment (Self-supervised learning regime)
![](https://github.com/OshriHalimi/unsupervised_learning_of_dense_shape_correspondence/blob/master/Capture.PNG)
In this experiment we show how the network can be optimized on a single pair of shapes and finally predict the correspondence.
The code for this experiment is located in the folder **\Single Pair Experiment**.
### Data
The 3D models we use in this experiment are provided in the folder **\artist_models**.
Note that the ground-truth crrespondences are unknown for this pair.

### Preprocessing
First create an empty folder with the name **\tf_artist** in the base directory **\Single Pair Experiment**.
Then run the script preprocess_artist_model.mat.
This will create the input data to the network in the folder **\tf_artist**, namely the geodesic distance matrices, the LBO eigenfunctions and the initial SHOT descriptors will be calculated.

### Training the netowrk
Run **train_FMnet_self_supervised.py**.
When the train is finished the checkpoint file will be saved in **\Results\artist_checkpoint**.

### Predicting the correspondence
First create an empty folder with the name **\unsupervised_artist_results** under the **\Results** directory.
Then, run **test_FMnet_self_supervised.py**. The network predictions will be saved in **\Results\unsupervised_artist_results**.

### Visualization
To visualize the results run **visualize_results.m**.
The folder contains additional script files: **visualize_unsupervised_network_results.m** and **visualize_supervised_network_results.m** that visualize the correspondence predicted (1) by the unsupervised network that was trained with the (unannotated) single pair, and (2) by the supervised network that was trained on faust synthetic human shapes. We provide the final predictions with each of these methods in the folders **Unsupervised Network Results** and **Supervised Network Results**. Additionally we provide code for comparison with few axiomatic algorithms. To calculate the predictions with SGMDS or FM+SHOT algorithm, run **SGMDS.m** or **SHOT_FM.m**, respectively. Further details for the single-pair experiment are provided in the paper.

## Learning Correspondence of Synthetic Shapes (Unsupervised)

![](https://github.com/OshriHalimi/unsupervised_learning_of_dense_shape_correspondence/blob/master/synFaustMen.jpg)

In this experiment we demostrate unsupervised learning of dense shape correspondence on a dataset of synthetic human shapes (MPI-FAUST). Link to the dataset: http://faust.is.tue.mpg.de/.
The code for this experiment is located in the folder **\Learning Correspondence of Synthetic Shapes\\** .

### Data
The 3D models we use in this experiment are provided in the folder **\faust_synthetic\shapes**.
We provide the original .ply files, as well as our generated .mat files. This code processes 3D models with the specific format of the .mat files, containing the vertices coordinates in the field **VERT**, the faces triangulation in the field **TRIV**, and the number of vertices and faces in the fields **n** and **m**, respectively. To convert the 3D model .ply files to this specific .mat format, please run the script **convert_ply_to_mat.m** in the folder that contains the .ply files (in this case we already ran it in the folder **\faust_synthetic\shapes** and provided the generated .mat files).

### Preprocessing
1. First, for each shape in faust synthetic shape collection we have to calculate the geodesic distance matrix.
To achieve this, please run the script **\faust_calc_distance_matrix.m**. This script will calculate the geodesic distance matrices and store them in a new folder **\faust_synthetic\distance_matrix**. This processing is done in parallel, using multiple matlab workers.
To view the geodesic distance from a source point, use the script **view_distance_matrix**. The result should be similar to this:

2. Next, for each shape we'll calculate LBO eigenfunctions and the initial SHOT descriptors. Please run the script **\faust_preprocess_shapes.m**. The results will be saved in a new folder **\faust_synthetic\network_data**.

### Training the network
To train the network, please run **train_FMnet_unsupervised.py**. The trained network will be saved in the folder **\Results\train_faust_synthetic**. You can edit the number of training iterations, defined in **train_FMnet_unsupervised.py**, here we use 3K mini-batch iterations.
* **Training loss**: During the training, we optimize the unsupervised loss and monitor the supervised loss for analysis purpose. When the training is finished, both losses are saves in **\Results\train_faust_synthetic\training_error.mat**. To visualize the losses during the training process - run the matlab script **visualize_synthetic_faust_test_results.m**. This script will produce a figure similar to figure 3 in the paper, showing a correlated decay of the unsupervised and the supervised losses.

### Predicting the correspondence on the test pairs
First create a list of all test pairs by calling the matlab script **create_test_pairs.m**. To test the network, please run **test_FMnet_unsupervised.py**, the test results will be saved in the folder **Results\test_faust_synthetic**.

### Visualization
To visualize the correspondence of a specific test pair, run the matlab script **visualize_synthetic_faust_test_results.m**.
Note that you should edit the indices of the test pair you wish to visualize in rows: 7,8 and 10. The result should look similar to this:

### Geodesic error evaluation
* **One pair**:
To evaluate the error curve for a specific pair of shapes, you need the the predicted correspondence between the shapes, the ground truth correspondence, and the geodesic distance matrix of the target shape. To calculate the error curve use the command (matlab):
```
    errs = calc_geo_err(matches, gt_matches, D_model);
    curve = calc_err_curve(errs, 0:0.001:1.0)/100;
    plot(0:0.001:1.0, curve); set(gca, 'xlim', [0 0.1]); set(gca, 'ylim', [0 1])
```
The functions **calc_geo_err** and **calc_err_curve** are located in the folder **\Tools**.

Here, **matches** is a vector such that
```matches[i]=j```

where **i** is a source vertex and **j** is the corresponding vertex in the target shape, according to the algorithm result.

Next, **gt_matches** is a vector such that ```gt_matches[i]=j```

where **i** is a source vertex and **j** is the corresponding vertex in the target shape, according to the ground truth.
For example, in synthetic faust:
```gt_matches = 1:6890;```

Finally, **D_model** is the distance matrix of the target shape.

To plot the geodesic error curve for a test pair, run the script **calculate_geodesic_error_synthetic_faust_test_results.m** after editing the indices of the test pair in rows: 7,8,10 and 13. The result should be similar to this:

* **Shape collection**: To evaluate the error curve for a collection of shapes you should average the error curves of all pairs of shapes, as follows:
```
CURVES = zeros(N_pairs,1001);
for i=1:NumberOfPairs
   %here you calculate matches, gt_matches and D_model, for each pair
   ...
   errs = calc_geo_err(matches, gt_matches, D_model);
   curve = calc_err_curve(errs, 0:0.001:1.0)/100;
   CURVES(i,:) = curve;
end

avg_curve_unsupervised = sum(CURVES,1)/ NumberOfPairs;
plot(0:0.001:1.0, avg_curve_unsupervised,'r'); set(gca, 'xlim', [0 0.1]); set(gca, 'ylim', [0 1])
```

To plot the average geodesic error **over all the intra pairs** in faust synthetic dataset, run **calculate_geodesic_error_intra.m**. The result should look like this:

To plot the average geodesic error **over all the inter pairs** in faust synthetic dataset, run **calculate_geodesic_error_inter.m**. The result should look like this:

### Optional Post-processing with PMF Algorithm (Product Manifold Filter)
TODO

## Learning Correspondence of Real Scans (Unsupervised)

TODO

## Learning Correspondence of Partial Shapes (Unsupervised)

TODO
### To be continued ...


text:
# Biblio search

This was my Capstone Stage 2 task while studying at udacity

Biblio search roughly translates to book search. It is an app that allows book lovers or (biblophiles) to search and discover new books they should read. The app draws data from the Google books API and present it to the user in a delightful manner.

## Tech Used
* MVVM
* Retrofit, GSON and OkHttp
* Glide
* LiveData
* ViewModel
* Room Database

## Next Steps
Because this was initially my Udacity project, I was limited to using some specific tools.
Some things I would like to do include:
* Refactor Codebase to Kotlin
* Use Coroutines or RXJava for async operations
* Add Paging Library support
* Dependency Injection (Preferably Hilt)

## Installation

Simply clone the repo and import into Android studio with gradle. Addition release links and Playstore links will be made available when ready.

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License
```
The MIT License (MIT)
Copyright (c) 2020 Robin
```


text:
Data types in Voxie
===================

Data types are normally stored as triple with base type, number of bits and
endianness.

Base types
----------

Valid base types are:
- `uint`: An unsigned integer.
- `int`: A signed integer in two's complement representation
- `bool`: Same as `uint`, but only 0 (false) and 1 (true) are valid values.
- `float` An IEEE 754-2008 'binary' representation of a floating point number.

Number of bits
--------------

The number of bits used for storing the value. Currently this must always be
a multiple of 8.

Endianness
----------

Can be one of the following values:
- `none`: Only valid if the number of bits is 8.
- `little`: Only valid if the number of bits is not 8, indicates little endian.
- `big`: Only valid if the number of bits is not 8, indicates big endian.
- `native`: In some contexts (e.g. when creating a new volume), `native` can
  be used to indicate the computers native endianness.

DBus
----

When transported over DBus, the data type is transported as `(sus)`, i.e.
a string (the base type), an unsigned 32-bit number (the number of bits) and
another string (the endianness).

repository: voxie-viewer/voxie

repo_name: voxie-viewer/voxie


text:
#Skrape{it} Examples
## How to use skrape{it}

Here you will find different example projects showcasing the power and elegant usage of skrape{it} 💪

## Android

The android sample is available [in this repository](https://github.com/skrapeit/skrape-android-sample).
Check the readme file to understand how to configure your environment.

## Scraping

The [scraping example](scraping) shows how to search over multiple urls for all links that contains a certain substring.
More specifically it searches a bunch [kotlinweekly newsletters](http://www.kotlinweekly.net) for hrefs that contain the substring "ktor", all wrapped in a coroutine to do the http requests in parallel.

## Pre-Release version usage

Need a new feature really urgent?
The [pre-release example](use-pre-release-version) show cases how to use jitpack releases directly taken from master commit even before official release to maven central has happened.

gha_language: Kotlin


text:
Virtual Assistant

Billion users around the world are on instant messaging and chat apps at any moment in time. People want and expect the instant engagement that only messaging apps can provide, and they’re rushing to these platforms in droves, at an adoption rate far greater than even social networks saw at their peak.  End users can easily discover and connect to assistants through many of the popular messaging apps, without the need to individually download and install them from an app store. Virtual Assistants have a distinct advantage over conventional device-resident Mobile Apps in many circumstances. With a Virtual Assistant, your service can be instantly available through the messaging app your user already has installed on their mobile device.

Unlike a simple chatbot, a Virtual Assistant can be equipped with multiple skills covering a broad set of domains and topics all from one conversational interface. There’s no need to search for the appropriate chatbot that supports a specific service. Your Virtual Assistant becomes the single help desk for all the conversational experiences you wish to provide to your employees and customers.

Virtual Assistant skills, powered by Artificial Intelligence (AI), dramatically improve the conversational experience, providing a very natural conversation between the assistant and the end user. Instead of the end user having to learn a fixed set of keywords that the assistant would respond to, a Virtual Assistant is able to understand the user’s intentions, however they are expressed and respond accordingly. A Virtual Assistant will ensure your users stay engaged and keep coming back to your service.

The application makes it simple and easy to build and train your Virtual Assistant without the need for specialist AI skills. Your assistant can then be exposed through many Chat and Voice channels, a custom mobile app or even your web site.

Natural Language Processing backed by Rasa nlu and core.

Virtual Assistant is build using following open source components.

- Angular Ui - To build, train and deploy a chat bot project
- Python API gateway - connecting to rasa for deploying and persisting training data
- Mongodb - for storing training data and editing training data

### Using Rasa

We use Rasa 1.3 as a ML framework to train and deploy virtual assistant.
We would keep updating the code base to support latest versions of Rasa.

We intent to support all features provided by Rasa framework, in case you find any feature missing please report to us.

### Documentation

You can find detailed documentation [here](https://navigateconsulting.github.io/virtual-assistant/)

## Installation

#### Quick Install

Virtual Assistant uses docker containers to build all application components.

##### Requirements
   - Docker version 18.09 onwards. (not tested on previous versions)
   - Docker Compose version 1.24 onwards (not tested on previous versions)
   - Linux Distributions (Windows not supported as of now, tested on ubuntu)

##### Installation

Clone the repo on local machine and build the docker containers as shown below.

    git clone https://github.com/navigateconsulting/virtual-assistant
    cd virtual-assistant
    docker-compose build
    docker-compose up

The Trainer application would now be avaliable on port 8080

#### Detailed Installation

   For detailed installation instructions please follow [this link](docs/installation/Readme.md)

## Usage
   Usage instructions : [click here](docs/usage/Readme.md)

## License

[Apache 2.0](LICENSE)

repository: dlrdlabs/virtual-assistant

repo_name: dlrdlabs/virtual-assistant


text:
Servinow standar installation
=============================

1) Clone the project:
---------------------
Clone the project to, for example, *~/git/servinowServer-jorge/*. I recommend **NOT** to use git plugin of netbeans and use instead [SmartGit](http://google.es). Clone your github fork using SSH. Don't add it to Netbeans as a new project yet.

I suggest you to use java7 for SmartGit (it instantly detects changes).

2) Install server
-----------------
I recommend use [Xampp Server](http://www.apachefriends.org/es/xampp.html) instead of a LAMP in linux. Just follow [installation instrucctions](http://www.apachefriends.org/en/xampp-linux.html#377).

3) Link your local copy
-----------------------

You can use a FTP account and when you want to test your project you can upload.  I recommend you directly use directly the working tree as a htdocs. So you can use this:

     $ sudo ln -s /home/$USER/git/servinowServer-jorge/ /opt/lampp/htdocs/servinowServer-jorge/

We have to add some file permissions to *app/cache* and *app/log*. Return to */home/$USER/git/servinowServer-jorge/* go to *app* directory and right click on cache dir and then select *Properties*. Select *Permission* tab and in *Other* section select:
     directory acces: Delete and remove files
wait 1 second.
     file access: read and write
wait 1 second.
Press the button "Apply permission to contained files" (or whatever). Then 1 second and close.

3) Configure your local copy of symfony:
----------------------------------------

In the working tree *app/config* there are a *parametersORIGINAL.yml*. **Copy** this file and rename it to *parameters.yml*. DON'T use Netbeans to copy the file because it ignores .gitignore file from git.

Configure it with your database info. If you have used xampp you can maintain the data because use the default credentials (user = root and no password).

4) Install all vendor dependencies of symfony2:
-----------------------------------------------

We need access to php executable so we have to add it to our $PATH:
    $ PATH=$PATH:/opt/lampp/bin/

Install first all vendor dependencies. So YOU HAVE TO download composer:

    curl -s https://getcomposer.org/installer | php

OR with "my way" (is the same as before but without the problem I had in Linux with curl):

    php composerInstaller.php

Then just install all vendor dependencies for symfony2:

    php composer.phar install

5) Checking your System Configuration:
-------------------------------------

To check if everything is OK symfony can check it for you. Execute its dependency checker:

    php app/check.php

Access the `config.php` script from a browser:

    http://localhost/path/to/symfony/app/web/config.php

If you get any warnings or recommendations, fix them before moving on. The recommendations are only recommendation. In last version of xampp I have two recommendation don't fixed and it is ok.

6) Add project to Netbeans
--------------------------
Download last version of netbeans for PHP (~50MB) and install it:
    $ sh netbeans*.sh

During the instalation I suggest you to use java6 or greater but *java7 is recommended*.

Add the project from source and use PHP 5.4 with that running configuration:
    Run as: Local Web Site (running on local web server) - (default option?)
    Project URL: http//localhost/servinowServer-jorge/ - (default option?)
    Index File: web/app_dev.php - (browse it)

The final url should be someting like this:
    http://localhost/servinowServer-jorge/web/app_dev.php/

You know where to ask any question. Thanks you.

repository: Servinow/servinowServer

repo_name: Servinow/servinowServer