问:
Conditional split showing error
Iam trying to split records into two tables using conditional split based on salary I am getting the following error

Error at conditional split the data type dt_wstr and dt_i4 are incompatible with for binary operator

答:
You have to add a type cast method

```<code>[COLUMN1] == (DT_WSTR,50)[COLUMN2]
</code>```

The error is thrown because you are comparing a string value to an integer value. Casting the integer value to string will solve the issue.

```<code>DT_WSTR : Unicode string
DT_I4 : Integer
</code>```

Title: Conditional split showing error

Body:
You have to add a type cast method

[COLUMN1] == (DT_WSTR,50)[COLUMN2]

The error is thrown because you are comparing a string value to an integer value. Casting the integer value to string will solve the issue.

DT_WSTR : Unicode string
DT_I4 : Integer


来源: stackexchange

问:
security user registration django rest endpoint
I want to implement a user registration endpoint using django rest framework. The endpoint would be public and anyone could potentially register a new user to be able to access the restricted version of the site. The registration endpoint would take a POST action and a JSON object containing let's say first name, last name, email and password. The problem is because of the nature of the endpoint being public someone could program a pyCurl script to create a bunch of new users, I want to avoid that. How can I secure my endpoint properly to avoid that? I have no idea at the moment on what course of action to take. I could make a registration page using CSRF and a django template. That could be a solution and let the rest of the application could run under angular2. Ideally I want to avoid that.

any ideas? thanks

答:
One solution would be to validate the email of the newly registered users. The created users would be set to inactive until they have validated their email address.
The validation can be done by sending a link containing a token and a UID (see the PasswordResetTokenGenerator from django) at their email address. By following this link, the user can activate his account and login to your site.

As for CSRF, you should always use it when sending data to your server (post, put, patch, etc)

ContentLicense: CC BY-SA 3.0


问:
Why can't Visual Studio 2010 Native C++ project do auto-completion?
I'm using Visual Studio 2010 Professional and a native (non-CLR) C++ project. I can not get auto-member-completion, auto parameter list, or any other intellisense related feature to work.  I've uninstalled and reinstalled the entire product, which is not a small task, yet still it refuses to work. I believe all the settings are at their defaults except some changes to the editor's colors.

Does anyone have any clue as to how I can get autocomplete working like it did in Visual Studio 2008?

EDIT: I created a native C++ console app and intellesense is working, for now. Who knowns when it will stop or why? My original project still has the issue. Is the problem program size? Number of lines of code? Number of files in the project? Including ATL headers? Orientation of the moon?

答: Though not necessarily the best way to fix this, but try installing a visual studio extension like visual assist, which enhances syntax highlighting. It might just help</p>

ContentLicense: CC BY-SA 2.5


问:
XAML Designer not showing up
In MS Visual Studio Express 2013 for Windows Desktop:

I'm learning C# and following an example that shows how to create a user interface in a .xaml file. https://msdn.microsoft.com/en-us/library/jj153219.aspx

It appears from the tutorial (see Figures 7 & 8) that there should be some windows showing the GUI. However, when I try to open the .xaml file in the Solution Explorer, View Code (Ctrl + Alt + 0) and View Designer (Shift + F7) both present the same thing: just the code. How do I open up the GUI box?

Update -- Here are the .xaml file contents. Note: I'm trying to open a new C# WPF Application. This is the stock code that Visual studio produces.

```<code><Window x:Class="WpfEvents.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>
</code>```

No XAML UI Designer option:

No Full XAML View Setting:

Thanks!

This is the version of Visual Studio that I downloaded. The description leads me to believe that the XAML UI Designer should be installed and that this shouldn't be an issue.

Express 2013 for Windows Desktop

Visual Studio Express for Windows Desktop lets you take full advantage of Windows with XAML designers, a productive IDE, and a variety of programming languages including C#, Visual Basic, and C++. Choose between Windows Presentation Foundation (WPF), Windows Forms, and Win32, to target the Windows desktop with the right technology for your application and your skills.

答:
Tools>Option>XAML Designer and enable XAML Designer worked for me.

PS: By default it is enabled. I disabled it due to VS performance issue and forgot about this change and end up facing same issue when I started working on WPF project.

Title: XAML Designer not showing up

Body:
In MS Visual Studio Express 2013 for Windows Desktop:

I'm learning C# and following an example that shows how to create a user interface in a .xaml file. https://msdn.microsoft.com/en-us/library/jj153219.aspx

It appears from the tutorial (see Figures 7 & 8) that there should be some windows showing the GUI. However, when I try to open the .xaml file in the Solution Explorer, View Code (Ctrl + Alt + 0) and View Designer (Shift + F7) both present the same thing: just the code. How do I open up the GUI box?

Update -- Here are the .xaml file contents. Note: I'm trying to open a new C# WPF Application. This is the stock code that Visual studio produces.

<Window x:Class="WpfEvents.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

No XAML UI Designer option:

No Full XAML View Setting:

Thanks!

This is the version of Visual Studio that I downloaded. The description leads me to believe that the XAML UI Designer should be installed and that this shouldn't be an issue.

Express 2013 for Windows Desktop

Visual Studio Express for Windows Desktop lets you take full advantage of Windows with XAML designers, a productive IDE, and a variety of programming languages including C#, Visual Basic, and C++. Choose between Windows Presentation Foundation (WPF), Windows Forms, and Win32, to target the Windows desktop with the right technology for your application and your skills.


问:
Customising error fields for Django log in templates
I'm semi-new to Django (but not new to Python or front end languages) - I'm just having a little trouble rendering required fields and error messages.

forms.py:

```<code>from django import forms
from django.contrib.auth import authenticate, login, logout

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        if username and not password:
            raise forms.ValidationError("Please enter a valid password...")
        elif not username and password:
            raise forms.ValidationError("I think you've forgotten to enter your username...")
        elif username and password:
            user = authenticate(username = username, password = password)
            if not user:
                raise forms.ValidationError("This user does not exist...")
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password...")
            if not user.is_active:
                raise forms.ValidationError("This user does not appear to be active.")

        return super(UserLoginForm, self).clean(*args, **kwargs)
</code>```

login_form.html:

```<code>    <form class="contact-form contact-form-two" name="contact-form" method="POST" action='' enctype='multipart/form-data'>
       {% csrf_token %}
       <div class="form-group">
          <input type="text" class="form-control" required="required" placeholder="User ID">
          <input type="password" class="form-control" required="required" placeholder="Password">
          <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button>
       </div>
    </form>
</code>```

Ignore the classes - I'm just borrowing from the default contact form I have created (at some point I will reorganise into one master "form" class.)

views.py:

```<code>from django.shortcuts import render
from django.contrib.auth import authenticate, get_user_model, login, logout

from .forms import UserLoginForm

# Create your views here.

def login_view(request):
    print(request.user.is_authenticated())
    title = "login"
    form = UserLoginForm(request.POST or None)

    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request, user)
        #Display the redirect if the form was valid and if user authentication was successful:
        print(request.user.is_authenticated())

    return render(request, "blog/user_auth/login_form.html", { "form": form, "title": title })
</code>```

Essentially, could anyone point me in the right direction for rendering the raised error messages that I have created within the template html?

The only examples online use pre-rendered django form html using the {{ form.as_p }} tag.

Any pro-tips on how to render these raised validation errors within the login_form would be gladly accepted!

答:
I think you can show form error in your login template like this</p>

```<code>{% if form.errors %}
<div class="alert alert-error">
  <h4>Please fix the following errors</h4>
  <ul>
    {% for field in form %}
      {% if field.errors %}
        {% for error in field.errors %}
          <li><a href="#id_{{ field.name }}" class="error">{{ error|escape }}</a></li>
        {% endfor %}
      {% endif %}
    {% endfor %}
  </ul>
</div>
{% endif %}
</code>```

Body:
I'm semi-new to Django (but not new to Python or front end languages) - I'm just having a little trouble rendering required fields and error messages.

forms.py:

from django import forms
from django.contrib.auth import authenticate, login, logout

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        if username and not password:
            raise forms.ValidationError("Please enter a valid password...")
        elif not username and password:
            raise forms.ValidationError("I think you've forgotten to enter your username...")
        elif username and password:
            user = authenticate(username = username, password = password)
            if not user:
                raise forms.ValidationError("This user does not exist...")
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password...")
            if not user.is_active:
                raise forms.ValidationError("This user does not appear to be active.")

        return super(UserLoginForm, self).clean(*args, **kwargs)

login_form.html:

    <form class="contact-form contact-form-two" name="contact-form" method="POST" action='' enctype='multipart/form-data'>
       {% csrf_token %}

          <input type="text" class="form-control" required="required" placeholder="User ID">
          <input type="password" class="form-control" required="required" placeholder="Password">
          <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button>

    </form>

Ignore the classes - I'm just borrowing from the default contact form I have created (at some point I will reorganise into one master "form" class.)

views.py:

from django.shortcuts import render
from django.contrib.auth import authenticate, get_user_model, login, logout

from .forms import UserLoginForm

# Create your views here.

def login_view(request):
    print(request.user.is_authenticated())
    title = "login"
    form = UserLoginForm(request.POST or None)

    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request, user)
        #Display the redirect if the form was valid and if user authentication was successful:
        print(request.user.is_authenticated())

    return render(request, "blog/user_auth/login_form.html", { "form": form, "title": title })

Essentially, could anyone point me in the right direction for rendering the raised error messages that I have created within the template html?

The only examples online use pre-rendered django form html using the {{ form.as_p }} tag.

Any pro-tips on how to render these raised validation errors within the login_form would be gladly accepted!

Body:
I think you can show form error in your login template like this

{% if form.errors %}
<div class="alert alert-error">
  <h4>Please fix the following errors</h4>
  <ul>
    {% for field in form %}
      {% if field.errors %}
        {% for error in field.errors %}
          <li><a href="#id_{{ field.name }}" class="error">{{ error|escape }}</a></li>
        {% endfor %}
      {% endif %}
    {% endfor %}
  </ul>
</div>
{% endif %}


问:
Wrapper datatype to store YEAR alone
I just want to store year value( for example 2011 or 2020) in a wrapper datatype. Which is the best suggested datatype? Is Integer wrapper type enough? </p>

答: Why not use the Year class, which is part of the JDK since Java 8? That way you also get a few useful methods for free (such as isLeap, length, ...).

Title: Wrapper datatype to store YEAR alone


问:
Makefile that recompiles only if its dependency actually changed
Let's imagine that I have a file that is generated based not on some other file in the file system, but some external command whose output may or may not change. Can I express this concept in the makefile and have dependent targets only run if the content actually changed?

To specific, I have a file date.h which has the current date, hour and minute (but not seconds), which is generated by a rule like this:

```<code>echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h
</code>```

The default 'app' target depends on date.h and the whole Makefile looks like:

```<code>app: date.h
    echo "Building app"
    touch app

date.h: FORCE
    echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

FORCE:
</code>```

Now the FORCE target causes date.h to be rebuild every time, which causes app to always be out of date and get rebuilt.

On the other hand, if I don't include the FORCE target, then date.h will only be rebuilt if it doesn't exist (e.g., after a clean or after initially cloning the project), but never again after that.

What I want is for date.h to be out of date only if its contents were actually changed by the echo - that is, when the minute changes, but not otherwise. Is there some way to tell make to only consider date.h changed if its actual bytes changed on disk, rather than going by the timestamp, or another way to achieve this effect?

Echoing the date to a temporary file and then conditionally updating date.h based on comparing their contents crossed my mind, but I'm not sure if it's a reasonable approach.

答:
I found another way, how to possibly solve this problem. The idea is this: You check for a temporary file, which is saved with date and time values. So, for the first time, you get a file like tmp/YYMMDDHHMM. When you run you Makefile again, then it is checked, if this files exists. If yes, do not create a new / do not update date.h. After a minute, if you run your Makefile again, a new file tmp/YYMMDDHHMM is generated and so date.h is updated:

```<code>TMP_DIR := tmp
RUN_OR_NOT := $(shell date '+%y%m%d%H%M')

all: ${TMP_DIR}/date.h

tmp_dir:
        mkdir -p ${TMP_DIR}

${TMP_DIR}/${RUN_OR_NOT}: tmp_dir
        if [ ! -f "${TMP_DIR}/${RUN_OR_NOT}" ]; then \
                echo "" > ${TMP_DIR}/${RUN_OR_NOT}; \
        fi;

${TMP_DIR}/date.h: ${TMP_DIR}/${RUN_OR_NOT}
        # create date.h
        @echo "Run date.h target, which creates date.h"
        touch ${TMP_DIR}/date.h

.PHONY: all special
</code>```

Body:
Let's imagine that I have a file that is generated based not on some other file in the file system, but some external command whose output may or may not change. Can I express this concept in the makefile and have dependent targets only run if the content actually changed?

To specific, I have a file date.h which has the current date, hour and minute (but not seconds), which is generated by a rule like this:

echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

The default 'app' target depends on date.h and the whole Makefile looks like:

app: date.h
    echo "Building app"
    touch app

date.h: FORCE
    echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

FORCE:

Now the FORCE target causes date.h to be rebuild every time, which causes app to always be out of date and get rebuilt.

On the other hand, if I don't include the FORCE target, then date.h will only be rebuilt if it doesn't exist (e.g., after a clean or after initially cloning the project), but never again after that.

What I want is for date.h to be out of date only if its contents were actually changed by the echo - that is, when the minute changes, but not otherwise. Is there some way to tell make to only consider date.h changed if its actual bytes changed on disk, rather than going by the timestamp, or another way to achieve this effect?

Echoing the date to a temporary file and then conditionally updating date.h based on comparing their contents crossed my mind, but I'm not sure if it's a reasonable approach.

Body:
I found another way, how to possibly solve this problem. The idea is this: You check for a temporary file, which is saved with date and time values. So, for the first time, you get a file like tmp/YYMMDDHHMM. When you run you Makefile again, then it is checked, if this files exists. If yes, do not create a new / do not update date.h. After a minute, if you run your Makefile again, a new file tmp/YYMMDDHHMM is generated and so date.h is updated:

TMP_DIR := tmp
RUN_OR_NOT := $(shell date '+%y%m%d%H%M')

all: ${TMP_DIR}/date.h

tmp_dir:
        mkdir -p ${TMP_DIR}

${TMP_DIR}/${RUN_OR_NOT}: tmp_dir
        if [ ! -f "${TMP_DIR}/${RUN_OR_NOT}" ]; then \
                echo "" > ${TMP_DIR}/${RUN_OR_NOT}; \
        fi;

${TMP_DIR}/date.h: ${TMP_DIR}/${RUN_OR_NOT}
        # create date.h
        @echo "Run date.h target, which creates date.h"
        touch ${TMP_DIR}/date.h

.PHONY: all special


问:
How can you index python functions for use in a for loop?
I'd like to figure out how to code the following pseudo-code:

```<code># Base-case
u_0(x) = x^3

for i in [0,5):
    u_(i+1)(x) = u_(i)(x)^2
</code>```

So that in the end I can call u_5(x), for example.

The difficulty I'm having with accomplishing the above is finding a way to index Python functions by i so that I can iteratively define each function.

I tried using recursion with two functions in place of indexing but I get "maximum recursion depth exceeded".

Here is a minimal working example:

```<code>import math
import sympy as sym

a,b = sym.symbols('x y')

def f1(x,y):
    return sym.sin(x) + sym.cos(y)*sym.tan(x*y)

for i in range(0,5):
    def f2(x,y):
    return sym.diff(f1(x,y),x) + sym.cos(sym.diff(f1(x,y),y,y))

    def f1(x,y):
        return f2(x,y)

print(f2(a,b))
</code>```

答:
The answer is actually pretty simple:

Pseudocode:

```<code>u_0(x) = x^3

for i in [0,5):
     u_(i+1)(x) = u_(i)(x)^2
</code>```

Actual code:

```<code>import sympy as sym

u = [None]*6 #Creates an empty array of 6 entries, i.e., u[0], u[1], ..., u[5]

x=sym.symbols('x')

u[0] = lambda x: x**3

for i in range(0,5):
    u[i+1] = lambda x, i=i: (u[i](x))**2 #the i=i in the argument of the lambda function is
     #necessary in Python; for more about this, see this question.

#Now, the functions are stores in the array u.  However, to call them (e.g., evaluate them,
#plot them, print them, etc) requires that we "lambdify" them, i.e., replace sympy
#functions with numpy functions, which the following for loop accomplishes:

for i in range(0,6):
    ulambdified[i] = sym.lambdify(x,u[i](x),"numpy")

for i in range(0,6):
    print(ulambdified[i](x))
</code>```

Body:
I'd like to figure out how to code the following pseudo-code:

# Base-case
u_0(x) = x^3

for i in [0,5):
    u_(i+1)(x) = u_(i)(x)^2

So that in the end I can call u_5(x), for example.

The difficulty I'm having with accomplishing the above is finding a way to index Python functions by i so that I can iteratively define each function.

I tried using recursion with two functions in place of indexing but I get "maximum recursion depth exceeded".

Here is a minimal working example:

import math
import sympy as sym

a,b = sym.symbols('x y')

def f1(x,y):
    return sym.sin(x) + sym.cos(y)*sym.tan(x*y)

for i in range(0,5):
    def f2(x,y):
    return sym.diff(f1(x,y),x) + sym.cos(sym.diff(f1(x,y),y,y))

    def f1(x,y):
        return f2(x,y)

print(f2(a,b))

Body:
The answer is actually pretty simple:

Pseudocode:

u_0(x) = x^3

for i in [0,5):
     u_(i+1)(x) = u_(i)(x)^2

Actual code:

import sympy as sym

u = [None]*6 #Creates an empty array of 6 entries, i.e., u[0], u[1], ..., u[5]

x=sym.symbols('x')

u[0] = lambda x: x**3

for i in range(0,5):
    u[i+1] = lambda x, i=i: (u[i](x))**2 #the i=i in the argument of the lambda function is
     #necessary in Python; for more about this, see this question.

#Now, the functions are stores in the array u.  However, to call them (e.g., evaluate them,
#plot them, print them, etc) requires that we "lambdify" them, i.e., replace sympy
#functions with numpy functions, which the following for loop accomplishes:

for i in range(0,6):
    ulambdified[i] = sym.lambdify(x,u[i](x),"numpy")

for i in range(0,6):
    print(ulambdified[i](x))


问:
django: celery vs channels vs in-view
Assume a button on my page which when clicked fires off an ajax request to my api endpoint which then fetches data from a 3rd party site. Let's say this task takes around 2-5 seconds with a timeout at 5 seconds. What's the ideal way to do this:

celery task.delay() in the api endpoint and return a url to poll every x intervals for the result.

just do it in the view

All tutorials I've seen suggest the celery way, but that seems like a lot of machinery/overhead for a simple request with minimal processing. Is there some generally accepted threshold (seconds till completion, etc..) in which one would choose one over the other?

Then there is django-channels which seems like it would be ideal for this. But, on first glance, the distinguishing line between channels workers and celery tasks seems blurred. Can I replace celery with the channels workers and just use that for the above stated task? Would channels also handle my longer running tasks? What would be the advantages/drawbacks with channels (either with celery or replacing celery)?

Finally, which of the 3 (celery/channels/in-view) would be the recommended approach to the example scenario given?

答:
I am not an expert on channels but here we go.

Channels is an abstraction above WSGI (the new protocol is ASGI) which allows you to communicate over "abstract" channels. Sometimes you'll do HTTP, sometimes websockets, sometimes other stuff you can do pretty much any communication pattern.

Celery is constructed in a similar manner, it uses a message bus (sometimes a more complex broker mechanism depending on how you run it) to send work to a worker machine which can send back optional results.

Now which do you choose?

In the view

I would avoid this unless you have a view specifically designed for this purpose. You will need to make sure that your stack can handle long-lived connections (heroku's router will complain if it takes more than 30 seconds for example) or you will want to implement some long polling interface.

With Celery

You'll need to do all of the setup to get things online.

Having a task whose results you want will require a result backend and passing the task ID around.

You'll need to implement a view that can query celery to figure out where the task is in terms of completion, success, etc..

Eg.

```<code># kick of the task somewhere

def create_task(request, *args, **kwargs):
    task_id = some_task.delay(param)
    return Response({'task_id': task_id})
</code>```

urls.py

```<code>url(r'^/tasks/<task_id>/$', name='task-progress')
</code>```

views.py

```<code>def task_progress_view(request, task_id):
    # get fancier here, this is just an example
    return Response(some_task.AsyncResult(task_id).state)
</code>```

That is a really simplistic example but that should do as a starting point.

With channels

You'll need to set up a bus, get the required views together in essentially the same way as celery, only you'll need to still have a piece of code that fetches the data with some retry, timeout logic, etc..

What to choose

Celery will take care of the work part, you'll have to take care of the updates and informing your client. Channels would be a reasonable way of dealing with that back and fourth but you may not need it.

I would think about what else you need to do. Most applications require asynchronous work at some point because business logic often dictates it. If you plan on using websockets and the like but you don't want to break down your django app into services I would just bite the bullet and do both.

If you don't need more than one protocol of communication, just use celery and do the views.

Title: django: celery vs channels vs in-view

Body:
I am not an expert on channels but here we go.

Channels is an abstraction above WSGI (the new protocol is ASGI) which allows you to communicate over "abstract" channels. Sometimes you'll do HTTP, sometimes websockets, sometimes other stuff you can do pretty much any communication pattern.

Celery is constructed in a similar manner, it uses a message bus (sometimes a more complex broker mechanism depending on how you run it) to send work to a worker machine which can send back optional results.

Now which do you choose?

In the view

I would avoid this unless you have a view specifically designed for this purpose. You will need to make sure that your stack can handle long-lived connections (heroku's router will complain if it takes more than 30 seconds for example) or you will want to implement some long polling interface.

With Celery

You'll need to do all of the setup to get things online.

Having a task whose results you want will require a result backend and passing the task ID around.

You'll need to implement a view that can query celery to figure out where the task is in terms of completion, success, etc..

Eg.

# kick of the task somewhere

def create_task(request, *args, **kwargs):
    task_id = some_task.delay(param)
    return Response({'task_id': task_id})

urls.py

url(r'^/tasks/<task_id>/$', name='task-progress')

views.py

def task_progress_view(request, task_id):
    # get fancier here, this is just an example
    return Response(some_task.AsyncResult(task_id).state)

That is a really simplistic example but that should do as a starting point.

With channels

You'll need to set up a bus, get the required views together in essentially the same way as celery, only you'll need to still have a piece of code that fetches the data with some retry, timeout logic, etc..

What to choose

Celery will take care of the work part, you'll have to take care of the updates and informing your client. Channels would be a reasonable way of dealing with that back and fourth but you may not need it.

I would think about what else you need to do. Most applications require asynchronous work at some point because business logic often dictates it. If you plan on using websockets and the like but you don't want to break down your django app into services I would just bite the bullet and do both.

If you don't need more than one protocol of communication, just use celery and do the views.


问:
wierd bug with vuejs 2 router
That is part of my axios request:

```<code>.then(function (response) {

    self.forms.process = false;

    if( response.data.redirect ){
        console.log(123);
        router.push( { name: response.data.redirect } );
    }

})
.catch(function (error) {
    console.log(error.response.data);
</code>```

if I remove router.push- no errors.
But with router.go I've got an error at console.log(error.response.data) line:

// here is printed 123 by console.log before router.push

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

I can't understand how to fix that bug

答: I should use self.$router.push instead of router.push</p>

Title: wierd bug with vuejs 2 router

Body:
That is part of my axios request:

.then(function (response) {

    self.forms.process = false;

    if( response.data.redirect ){
        console.log(123);
        router.push( { name: response.data.redirect } );
    }

})
.catch(function (error) {
    console.log(error.response.data);

if I remove router.push- no errors.
But with router.go I've got an error at console.log(error.response.data) line:

// here is printed 123 by console.log before router.push

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

I can't understand how to fix that bug


问:
How do I export to the same network drive that we start from using vba in excel?
This is my first post at stackoverflow but I appreciate all the help I've received just doing searches. Alas, I'm not able to find an answer to this next question, possibly because I don't know the right words to use.

Here's my dilemma, and then I'll post the code.

In this part of our process:

we edit an .xlsx file,

then export it as a .csv

then save it to the same directory where the .xlsx is located.

We use a shared drive, with two mapped network drives (each mapped drive is for a different set of clients).

I created a macro to see how Excel would code it (see below), but each time we edit the file, the location will change because it's a different job or perhaps a different client.  Here is the macro "closefile".

Macro

```<code>Sub CloseFile()
'
' CLOSEFILE Macro
' CLOSES THE FILE IN THE SAME LOCATION AS THE XLS...HOPEFULLY
'
' Keyboard Shortcut: Ctrl+Shift+I
'
    ChDir _
        **"Z:\@Client Jobs\House\13579\Folder 3"**
    ActiveWorkbook.SaveAs fileName:= _
        **"Z:\@Client Jobs\House\13579\Folder 3\13579.stage.csv"** _
        , FileFormat:=xlCSV, CreateBackup:=False
End Sub

End of Macro
</code>```

Any suggestions on how we can export the csv to the same directory that we start from when we edit the .xlsx?

Rico

答:
Thanks for your help.  This code did everything I wanted. I added the "close file" option at the end:

Sub CloseFile()
  With ActiveWorkbook
    .SaveAs fileName:=Left(.FullName, InStrRev(.FullName, ".")) & "csv", FileFormat:=xlCSV
  End With
ActiveWorkbook.Close False
End Sub

Body:
This is my first post at stackoverflow but I appreciate all the help I've received just doing searches. Alas, I'm not able to find an answer to this next question, possibly because I don't know the right words to use.

Here's my dilemma, and then I'll post the code.

In this part of our process:

we edit an .xlsx file,

then export it as a .csv

then save it to the same directory where the .xlsx is located.

We use a shared drive, with two mapped network drives (each mapped drive is for a different set of clients).

I created a macro to see how Excel would code it (see below), but each time we edit the file, the location will change because it's a different job or perhaps a different client.  Here is the macro "closefile".

Macro

Sub CloseFile()
'
' CLOSEFILE Macro
' CLOSES THE FILE IN THE SAME LOCATION AS THE XLS...HOPEFULLY
'
' Keyboard Shortcut: Ctrl+Shift+I
'
    ChDir _
        **"Z:\@Client Jobs\House\13579\Folder 3"**
    ActiveWorkbook.SaveAs fileName:= _
        **"Z:\@Client Jobs\House\13579\Folder 3\13579.stage.csv"** _
        , FileFormat:=xlCSV, CreateBackup:=False
End Sub

End of Macro

Any suggestions on how we can export the csv to the same directory that we start from when we edit the .xlsx?

Rico


问:
Ploting RMSE and RSquared separately using postResample
I want to print in a plot the correlation between pred x obs, the RMSE and Rsquared. When I calculate using "postResample", I get both values together, but I want them separated. So when I ask R to plot, it plots everything together. Could somebody help plotting it separated?</p>

```<code>## Ploting residuals
axisRange <- extendrange(c(observed, predicted))
plot(observed, predicted,
 ylim = axisRange,
 xlim = axisRange,
 ylab = 'Predicted',
 xlab = 'Observed', las=1)

 ## correlation predicted x observed
 inform = as.character(round(cor(predicted, observed), digits = 2))
 text(x=10,y=46, paste('Corr =', inform))
 text(x=10,y=43, paste('RMSE =', inform))
 text(x=10,y=40, paste('RSquared =', inform))

 ## Adding reference line
 abline(0, 1, col = "darkgrey", lty = 2)

 ## Calculating Rsquared and RMSE
 postResample(predicted, observed)
</code>```

答:
You can use the [] to access the first (RMSE) and the second (R squared) elements of the output of the function postResample().

Here is an example:

```<code>postResample(1:10,9:18)[1]

postResample(1:10,9:18)[2]
</code>```

So in your code:

```<code>## Ploting residues
axisRange <- extendrange(c(observed, predicted))
plot(observed, predicted,
 ylim = axisRange,
 xlim = axisRange,
 ylab = 'Predicted',
 xlab = 'Observed', las=1)

 ## correlation predicted x observed
 inform = as.character(round(cor(predicted, observed), digits = 2))
 text(x=10,y=46, paste('Corr =', inform))
 text(x=10,y=43, paste('RMSE =', postResample(predicted, observed)[1]))
 text(x=10,y=40, paste('RSquared =', postResample(predicted, observed)[2]))

 ## Adding reference line
 abline(0, 1, col = "darkgrey", lty = 2)
</code>```

Body:
I want to print in a plot the correlation between pred x obs, the RMSE and Rsquared. When I calculate using "postResample", I get both values together, but I want them separated. So when I ask R to plot, it plots everything together. Could somebody help plotting it separated?

## Ploting residuals
axisRange <- extendrange(c(observed, predicted))
plot(observed, predicted,
 ylim = axisRange,
 xlim = axisRange,
 ylab = 'Predicted',
 xlab = 'Observed', las=1)

 ## correlation predicted x observed
 inform = as.character(round(cor(predicted, observed), digits = 2))
 text(x=10,y=46, paste('Corr =', inform))
 text(x=10,y=43, paste('RMSE =', inform))
 text(x=10,y=40, paste('RSquared =', inform))

 ## Adding reference line
 abline(0, 1, col = "darkgrey", lty = 2)

 ## Calculating Rsquared and RMSE
 postResample(predicted, observed)

Body:
You can use the [] to access the first (RMSE) and the second (R squared) elements of the output of the function postResample().

Here is an example:

postResample(1:10,9:18)[1]

postResample(1:10,9:18)[2]

So in your code:

## Ploting residues
axisRange <- extendrange(c(observed, predicted))
plot(observed, predicted,
 ylim = axisRange,
 xlim = axisRange,
 ylab = 'Predicted',
 xlab = 'Observed', las=1)

 ## correlation predicted x observed
 inform = as.character(round(cor(predicted, observed), digits = 2))
 text(x=10,y=46, paste('Corr =', inform))
 text(x=10,y=43, paste('RMSE =', postResample(predicted, observed)[1]))
 text(x=10,y=40, paste('RSquared =', postResample(predicted, observed)[2]))

 ## Adding reference line
 abline(0, 1, col = "darkgrey", lty = 2)


问:
p5.js | Syntaxe issue
I made a processing animation, but I don't know how to convert a part of this into Javascript (i'm using p5).

Here is my actual code :

```<code>var NUM_LINES = 10;
var j;
var t;

function setup() {
    createCanvas(200,200);
    background(20);
}

function draw() {
    background(255);
    strokeWeight(1);

    translate(width/2, height/2);

    for (var i = 0; i < NUM_LINES; i++) {
        stroke(60, 60, 60);
        line(x1(t + i), y1(t + i), x2(t + i), y2(t + i));
    }

    t += 0.5;
}

float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

float y1(float t){
    return cos(t / 10) * 35;
}

float x2(float t){
    return sin(t / 10) * 70 + sin(t) * 2;
}

float y2(float t){
    return cos(t / 20) * 70 + cos(t / 12) * 20 ;
}
}
</code>```

Do you know how to convert this code below into javascript ?

```<code>float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}
</code>```

答:
You don't convert code by just translating it line by line. You translate code by understanding exactly what it's doing, and then figuring out how to do that in your target language.

But just looking at your function:

```<code>float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}
</code>```

This defines a function named x1 that takes a parameter named t and then does some stuff that should be pretty much the same in every language. So it might look like this:

```<code>function x1(t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}
</code>```

Note that there are multiple ways to do this, so you could also do something like this:

```<code>var x1 = function(t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}
</code>```

You really should take a step back and learn some JavaScript basics instead of trying to translate things one line at a time.

Title: p5.js | Syntaxe issue

Body:
I made a processing animation, but I don't know how to convert a part of this into Javascript (i'm using p5).

Here is my actual code :

var NUM_LINES = 10;
var j;
var t;

function setup() {
    createCanvas(200,200);
    background(20);
}

function draw() {
    background(255);
    strokeWeight(1);

    translate(width/2, height/2);

    for (var i = 0; i < NUM_LINES; i++) {
        stroke(60, 60, 60);
        line(x1(t + i), y1(t + i), x2(t + i), y2(t + i));
    }

    t += 0.5;
}

float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

float y1(float t){
    return cos(t / 10) * 35;
}

float x2(float t){
    return sin(t / 10) * 70 + sin(t) * 2;
}

float y2(float t){
    return cos(t / 20) * 70 + cos(t / 12) * 20 ;
}
}

Do you know how to convert this code below into javascript ?

float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

Body:
You don't convert code by just translating it line by line. You translate code by understanding exactly what it's doing, and then figuring out how to do that in your target language.

But just looking at your function:

float x1(float t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

This defines a function named x1 that takes a parameter named t and then does some stuff that should be pretty much the same in every language. So it might look like this:

function x1(t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

Note that there are multiple ways to do this, so you could also do something like this:

var x1 = function(t){
    return sin(t / 10) * 35 + sin(t / 5) * 20;
}

You really should take a step back and learn some JavaScript basics instead of trying to translate things one line at a time.


问:
AWS error from Python: No module named lambda_function
I am creating a AWS Lambda python deployment package. I am using one external dependency requests. I installed the external dependency using the AWS documentation. Below is my Python code.

```<code>import requests

print('Loading function')

s3 = boto3.client('s3')

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        s3.download_file(bucket,key, '/tmp/data.txt')
        lines = [line.rstrip('\n') for line in open('/tmp/data.txt')]
        for line in lines:
            col=line.split(',')
            print(col[5],col[6])
        print("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e
</code>```

Created the Zip the content of the project-dir directory and uploaded to the lambda(Zip the directory content, not the directory). When I am execute the function I am getting the below mentioned error.

```<code>START RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058 Version: $LATEST
**Unable to import module 'lambda_function': No module named lambda_function**

END RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058
REPORT RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058  Duration: 19.63 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 9 MB
</code>```

答: If you are uploading a zip file. Make sure that you are zipping the contents of the directory and not the directory itself. </p>

ContentLicense: CC BY-SA 4.0

Body:
I am creating a AWS Lambda python deployment package. I am using one external dependency requests. I installed the external dependency using the AWS documentation. Below is my Python code.

import requests

print('Loading function')

s3 = boto3.client('s3')

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        s3.download_file(bucket,key, '/tmp/data.txt')
        lines = [line.rstrip('\n') for line in open('/tmp/data.txt')]
        for line in lines:
            col=line.split(',')
            print(col[5],col[6])
        print("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

Created the Zip the content of the project-dir directory and uploaded to the lambda(Zip the directory content, not the directory). When I am execute the function I am getting the below mentioned error.

START RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058 Version: $LATEST
**Unable to import module 'lambda_function': No module named lambda_function**

END RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058
REPORT RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058  Duration: 19.63 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 9 MB


问:
Looping over a python list of tuples and applying a function
I have a data frame in this format:

```<code>  vid            points
0 1              [[0,1], [0,2, [0,3]]
1 2              [[1,2], [1,4], [1,9], [1,7]]
2 3              [[2,1], [2,3], [2,8]]
3 4              [[3,2], [3,4], [3,5],[3,6]]
</code>```

Each row is trajectory data, and I have to find distance between the trajectories with a function func_dist, like this:

```<code> x = df.iloc[0]["points"].tolist()
 y = df.iloc[3]["points"].tolist()
 func_dist(x, y)
</code>```

I have a list l of indices for trajectories of interest..

```<code>l = [0,1,3]
</code>```

I must find the distance between all the possible pairs of trajectories; in the case above, this is 0-1, 0-3, and 1-3.  I know how to generate a list of pairs using

```<code> pairsets = list(itertools.combinations(l, 2))
</code>```

which returns

```<code> [(0,1), (0,3), (1,3)]
</code>```

Since the list may have over 100 indices, I am trying to automate this process and store the distances calculated between each pair in a new_df data frame.

I tried the following code for distance computation:

```<code>for pair in pairsets:
    a, b = [m[0] for m in pairssets], [n[1] for n in pairsets]
    for i in a:
        x = df.iloc[i]["points"].tolist()
    for j in b:
        y = df.iloc[j]["points"].tolist()
    dist = func_dist(x, y)
</code>```

But it calculates only the last pair, 1-3.  How to calculate all of the pairs and create a new data frame like this:

```<code>  traj1       traj2       distance
  0           1           some_val
  0           3           some_val
  1           3           some_val
</code>```

答:
This is simply a matter of handling your indices properly.
For each pair, you grab the two indices, assign your data sets, and compute the distance.

```<code>dist_table = []

for pair in pairsets:
    i, j = pair
    x = df.iloc[i]["points"].tolist()
    y = df.iloc[j]["points"].tolist()
    dist = func_dist(x, y)
    dist_table.append( [i, j, dist] )
</code>```

You can combine the first two lines:

```<code>for i, j in pairsets:
</code>```

The dist_table gives you a 2D list that you should be able to convert to a new data frame with a simple PANDAS call.

Does that get you moving?

Body:
I have a data frame in this format:

  vid            points
0 1              [[0,1], [0,2, [0,3]]
1 2              [[1,2], [1,4], [1,9], [1,7]]
2 3              [[2,1], [2,3], [2,8]]
3 4              [[3,2], [3,4], [3,5],[3,6]]

Each row is trajectory data, and I have to find distance between the trajectories with a function func_dist, like this:

 x = df.iloc[0]["points"].tolist()
 y = df.iloc[3]["points"].tolist()
 func_dist(x, y)

I have a list l of indices for trajectories of interest..

l = [0,1,3]

I must find the distance between all the possible pairs of trajectories; in the case above, this is 0-1, 0-3, and 1-3.  I know how to generate a list of pairs using

 pairsets = list(itertools.combinations(l, 2))

which returns

 [(0,1), (0,3), (1,3)]

Since the list may have over 100 indices, I am trying to automate this process and store the distances calculated between each pair in a new_df data frame.

I tried the following code for distance computation:

for pair in pairsets:
    a, b = [m[0] for m in pairssets], [n[1] for n in pairsets]
    for i in a:
        x = df.iloc[i]["points"].tolist()
    for j in b:
        y = df.iloc[j]["points"].tolist()
    dist = func_dist(x, y)

But it calculates only the last pair, 1-3.  How to calculate all of the pairs and create a new data frame like this:

  traj1       traj2       distance
  0           1           some_val
  0           3           some_val
  1           3           some_val

Body:
This is simply a matter of handling your indices properly.
For each pair, you grab the two indices, assign your data sets, and compute the distance.

dist_table = []

for pair in pairsets:
    i, j = pair
    x = df.iloc[i]["points"].tolist()
    y = df.iloc[j]["points"].tolist()
    dist = func_dist(x, y)
    dist_table.append( [i, j, dist] )

You can combine the first two lines:

for i, j in pairsets:

The dist_table gives you a 2D list that you should be able to convert to a new data frame with a simple PANDAS call.

Does that get you moving?


问:
Improve service method with elixir Processes and Supervisors
I'm building a service that will be making requests to two external APIs. The results are persisted in the local database.

Roughly, the method should work like this:

```<code>def make_requests(conn, params) do
  case Service1.request(params) do
    {:ok, response1 } ->
      case Service2.request(params) do
        {:ok, response2 } ->
          conn
          |> Repo.insert(response1)
          |> Repo.insert(response2)
          |> render("show.json")
        {:error, message} ->
          conn |> render("error.json")
      end
    {:error, message } ->
      conn |> render("error.json")
  end
end
</code>```

New to elixir, I've been reading about Processes and Supervisors. My question is: Does is make sense to use them here? Could I make the method faster, more performing, or maybe improve fault tolerance by implementing them here?

答:
Since you asked specifically whether this could improve performance or fault tolerance, I think the answer if yes. You can use Task.async to perform the requests in parallel since it doesn't look like the requests depend on each other. Same for the database inserts. I would probably use a Task.Supervisor here. You can also configure it to retry in case of failure, just be careful not to end up with duplicates by ensuring the requests and database inserts are idempotent.

For example,

```<code>import Supervisor.Spec

children = [
  supervisor(Task.Supervisor, [[name: ExampleApp.TaskSupervisor, restart: :transient]]),
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
</code>```

Then,

```<code>{:ok, pid} = Task.Supervisor.start_child(ExampleApp.TaskSupervisor, fn ->
  {:ok, response} = Service1.request(params)
  Repo.insert(response)
end)
{:ok, pid} = Task.Supervisor.start_child(ExampleApp.TaskSupervisor, fn ->
  {:ok, response} = Service2.request(params)
  Repo.insert(response)
end)
</code>```

Body:
I'm building a service that will be making requests to two external APIs. The results are persisted in the local database.

Roughly, the method should work like this:

def make_requests(conn, params) do
  case Service1.request(params) do
    {:ok, response1 } ->
      case Service2.request(params) do
        {:ok, response2 } ->
          conn
          |> Repo.insert(response1)
          |> Repo.insert(response2)
          |> render("show.json")
        {:error, message} ->
          conn |> render("error.json")
      end
    {:error, message } ->
      conn |> render("error.json")
  end
end

New to elixir, I've been reading about Processes and Supervisors. My question is: Does is make sense to use them here? Could I make the method faster, more performing, or maybe improve fault tolerance by implementing them here?

Body:
Since you asked specifically whether this could improve performance or fault tolerance, I think the answer if yes. You can use Task.async to perform the requests in parallel since it doesn't look like the requests depend on each other. Same for the database inserts. I would probably use a Task.Supervisor here. You can also configure it to retry in case of failure, just be careful not to end up with duplicates by ensuring the requests and database inserts are idempotent.

For example,

import Supervisor.Spec

children = [
  supervisor(Task.Supervisor, [[name: ExampleApp.TaskSupervisor, restart: :transient]]),
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)

Then,

{:ok, pid} = Task.Supervisor.start_child(ExampleApp.TaskSupervisor, fn ->
  {:ok, response} = Service1.request(params)
  Repo.insert(response)
end)
{:ok, pid} = Task.Supervisor.start_child(ExampleApp.TaskSupervisor, fn ->
  {:ok, response} = Service2.request(params)
  Repo.insert(response)
end)


问:
Change jQuery depending on where user is on page
I'm trying to make a navigation where the background comes in after the user scrolls down. However, when the user is in the middle of the page, and refreshes, the background disappears and they need to scroll again for it to reappear. I'm trying to make it so whenever the user has scrolled past the header, the navigation background colour will be there no matter what.

Any help would be appreciated!

Code:

Jquery:

```<code>    $(document).ready(function(){
  var targetOffset = $('header').offset().top + $('header').height();

  var $w = $(window).scroll(function(){
      if ( $w.scrollTop() > targetOffset ) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
      } else {
        $('#nav').css('background-color', 'rgba(35,46,63,0)');
      }
  });
});
</code>```

CSS:

```<code>nav {
    background-color: rgba(35,46,63,0);
    transition: background-color 200ms linear;
    position: fixed;
    left: 0;
    right: 0;
    padding: 25px;
    z-index: 1;
    box-shadow: 0px 0px 0px rgba(0,0,0,0);
}

nav > .wrapper {
    overflow: hidden;
}

nav > .wrapper > li.nav-logo {
    list-style: none;
    font-weight: 600;
    padding: 0px;
    border-top: 1px solid rgba(0,0,0,0);
}

nav > .wrapper > li.nav-logo > a {
    color: #DDDDDD;
    text-decoration: none;
}

nav > .wrapper > li.nav-logo > a > img.left {
    width: 5%;
    display: inline-block;
    float: left;
}

nav > .wrapper > ul.right {
    list-style: none;
    float: right;
}

nav > .wrapper > ul > li {
    display: inline-block;
    list-style: none;
    font-weight: 400;
    font-size: 0.9em;
    padding: 15px;
    border-bottom: 1px solid rgba(0,0,0,0);
    border-radius: 6px;
    vertical-align: middle;
    transition: all 0.3s ease;
}

nav > .wrapper > ul > li > a {
    color: #FFFFFF;
    text-decoration: none;
    transition: all .3s ease;
}

nav > .wrapper > ul > li > a:hover {
    color: white;
    text-decoration: none;
}
</code>```

HTML:

```<code><nav id="nav">
    <div class="wrapper">
        <li class="nav-logo"><a href="#"><img class="left" src="assets/images/ugn-logos/single-ugn-logo.png" alt="ugn-logo"></a></li>
        <span class="nav-btn"><i class="icon-menu"></i></span>
        <ul class="right">
            <li><a href="index.html">Home</a></li>
            <li><a href="shared-hosting.html">Shared Hosting</a></li>
            <li><a href="vps.html">VPS</a></li>
            <li><a href="minecraft.html">Minecraft</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>
</nav>
</code>```

答:
you can try this</p>

```<code>$( document ).load(function(){ /* your code */ });
</code>```

Body:
I'm trying to make a navigation where the background comes in after the user scrolls down. However, when the user is in the middle of the page, and refreshes, the background disappears and they need to scroll again for it to reappear. I'm trying to make it so whenever the user has scrolled past the header, the navigation background colour will be there no matter what.

Any help would be appreciated!

Code:

Jquery:

    $(document).ready(function(){
  var targetOffset = $('header').offset().top + $('header').height();

  var $w = $(window).scroll(function(){
      if ( $w.scrollTop() > targetOffset ) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
      } else {
        $('#nav').css('background-color', 'rgba(35,46,63,0)');
      }
  });
});

CSS:

nav {
    background-color: rgba(35,46,63,0);
    transition: background-color 200ms linear;
    position: fixed;
    left: 0;
    right: 0;
    padding: 25px;
    z-index: 1;
    box-shadow: 0px 0px 0px rgba(0,0,0,0);
}

nav > .wrapper {
    overflow: hidden;
}

nav > .wrapper > li.nav-logo {
    list-style: none;
    font-weight: 600;
    padding: 0px;
    border-top: 1px solid rgba(0,0,0,0);
}

nav > .wrapper > li.nav-logo > a {
    color: #DDDDDD;
    text-decoration: none;
}

nav > .wrapper > li.nav-logo > a > img.left {
    width: 5%;
    display: inline-block;
    float: left;
}

nav > .wrapper > ul.right {
    list-style: none;
    float: right;
}

nav > .wrapper > ul > li {
    display: inline-block;
    list-style: none;
    font-weight: 400;
    font-size: 0.9em;
    padding: 15px;
    border-bottom: 1px solid rgba(0,0,0,0);
    border-radius: 6px;
    vertical-align: middle;
    transition: all 0.3s ease;
}

nav > .wrapper > ul > li > a {
    color: #FFFFFF;
    text-decoration: none;
    transition: all .3s ease;
}

nav > .wrapper > ul > li > a:hover {
    color: white;
    text-decoration: none;
}

HTML:

Home

Shared Hosting

VPS

Minecraft

Contact

Body:
you can try this

$( document ).load(function(){ /* your code */ });


问:
Qt drawing a ring / circle with a hole
I need to draw a circle with QPainter. When I used drawEllipse function like :

```<code>void UserClass::Draw(QPainter &painter) {

    painter.save();
    painter.setBrush( GetColor() );
    QPoint centerPosition = GetCenterPosition();
    painter.drawEllipse( centerPosition, m_CircleOuterRadius, m_CircleOuterRadius);
    painter.setBrush(QColor(0, 0, 0, 0));
    painter.drawEllipse( centerPosition, m_CircleInnerRadius, m_CircleInnerRadius);
    painter.restore();
}
</code>```

Unfortunately result is not what I desired. I want to have inner circle not be filled. That is why I put alpha value as zero but ofcourse it didn't work. How can I have a circle which is not until a certain radius with qt ?

答:
You should create a QPainterPath then add the two circles to it via addEllipse(), the outer first, then the inner. This will effectively give you a shape that is the outer circle with the inner circle punched as a hole.

Then you fill the painter path with a green brush, which will result in a hollow ring. Afterwards, if you want the white outlines, you can stroke the path with a white pen as well.

Also note that the painter path can be created only once and stored for reuse instead of creating it anew every time you redraw.

Title: Qt drawing a ring / circle with a hole

Body:
I need to draw a circle with QPainter. When I used drawEllipse function like :

void UserClass::Draw(QPainter &painter) {

    painter.save();
    painter.setBrush( GetColor() );
    QPoint centerPosition = GetCenterPosition();
    painter.drawEllipse( centerPosition, m_CircleOuterRadius, m_CircleOuterRadius);
    painter.setBrush(QColor(0, 0, 0, 0));
    painter.drawEllipse( centerPosition, m_CircleInnerRadius, m_CircleInnerRadius);
    painter.restore();
}

Unfortunately result is not what I desired. I want to have inner circle not be filled. That is why I put alpha value as zero but ofcourse it didn't work. How can I have a circle which is not until a certain radius with qt ?


问:
why passing in a temp variable into const ref in ctor work?
```<code>// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout << p->d_member << std::endl;

    return 0;
}
</code>```

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?

答: Your constructor initialization list copies the integer argument to the member variable.  The lifetime of your member variable is the lifetime of your object.

Body:
// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout <
d_member << std::endl;

    return 0;
}

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?


问:
Wrong formatting in BlockSyntax of the method body
I wrote code which generate a class for WebAPI controller methods calling. When I try to generated method body I have problems with strings formatting like this:

```<code>    public async Task<String> HttpPost(Boolean isSuccess)
    {
            var taskCompletion = new TaskCompletionSource<IRestResponse>(); var  request  =  RestSharpExtensions . PostRequest ( "Test" ,  "HttpPost" ,  isSuccess . ToString ( ) ) ;  var  handle  =  Client . ExecuteAsync ( request ,  r  =>  taskCompletion . SetResult ( r ) ) ;  var  response  =  await  taskCompletion . Task ;  return  JsonConvert . DeserializeObject < String > ( response . Content ) ;
    }
</code>```

This is the method which generated method body:

```<code>    private static BlockSyntax GetMethodBody(BaseApiMethodInfo methodInfo, string controllerName)
    {
        var body = new StringBuilder($"var taskCompletion = new TaskCompletionSource<IRestResponse>();{Environment.NewLine}var request = ");
        var dataText = methodInfo.Data != null
            ? methodInfo.Data.Item2.ToString()
            : "null";

        var methodParameters = $"\"{controllerName}\", \"{methodInfo.Name}\", {dataText}.ToString()";
        string httpRequestText;
        switch (methodInfo.Method)
        {
            case Method.GET:
                httpRequestText = $"RestSharpExtensions.GetRequest({methodParameters});";
                break;
            case Method.POST:
                httpRequestText = $"RestSharpExtensions.PostRequest({methodParameters});";
                break;
            case Method.PUT:
                httpRequestText = $"RestSharpExtensions.PutRequest({methodParameters});";
                break;
            case Method.DELETE:
                httpRequestText = $"RestSharpExtensions.DeleteRequest({methodParameters});";
                break;
            default:
                throw new ArgumentException("methodInfo.Method");
        }

        body.AppendLine(httpRequestText + Environment.NewLine);
        body.AppendLine($"var handle = Client.ExecuteAsync(request, r => taskCompletion.SetResult(r));{Environment.NewLine}");
        body.AppendLine($"var response = await taskCompletion.Task;{Environment.NewLine}");
        body.AppendLine($"return JsonConvert.DeserializeObject<{TypesHelper.GetTypeName(methodInfo.ReturnedType)}>(response.Content);");

        return Block(ParseStatement(body.ToString()));
    }
</code>```

Unfortunately i did't find any points to solve this problem. This is the referense to github repo:
https://github.com/ddydeveloper/Roslyn.ApiClient.Codegen

Did anyone have such problem?

答: Call Formatter.FormatAsync() to run Roslyn's formatter.

Body:
I wrote code which generate a class for WebAPI controller methods calling. When I try to generated method body I have problems with strings formatting like this:

    public async Task<String> HttpPost(Boolean isSuccess)
    {
            var taskCompletion = new TaskCompletionSource<IRestResponse>(); var  request  =  RestSharpExtensions . PostRequest ( "Test" ,  "HttpPost" ,  isSuccess . ToString ( ) ) ;  var  handle  =  Client . ExecuteAsync ( request ,  r  =>  taskCompletion . SetResult ( r ) ) ;  var  response  =  await  taskCompletion . Task ;  return  JsonConvert . DeserializeObject < String > ( response . Content ) ;
    }

This is the method which generated method body:

    private static BlockSyntax GetMethodBody(BaseApiMethodInfo methodInfo, string controllerName)
    {
        var body = new StringBuilder($"var taskCompletion = new TaskCompletionSource<IRestResponse>();{Environment.NewLine}var request = ");
        var dataText = methodInfo.Data != null
            ? methodInfo.Data.Item2.ToString()
            : "null";

        var methodParameters = $"\"{controllerName}\", \"{methodInfo.Name}\", {dataText}.ToString()";
        string httpRequestText;
        switch (methodInfo.Method)
        {
            case Method.GET:
                httpRequestText = $"RestSharpExtensions.GetRequest({methodParameters});";
                break;
            case Method.POST:
                httpRequestText = $"RestSharpExtensions.PostRequest({methodParameters});";
                break;
            case Method.PUT:
                httpRequestText = $"RestSharpExtensions.PutRequest({methodParameters});";
                break;
            case Method.DELETE:
                httpRequestText = $"RestSharpExtensions.DeleteRequest({methodParameters});";
                break;
            default:
                throw new ArgumentException("methodInfo.Method");
        }

        body.AppendLine(httpRequestText + Environment.NewLine);
        body.AppendLine($"var handle = Client.ExecuteAsync(request, r => taskCompletion.SetResult(r));{Environment.NewLine}");
        body.AppendLine($"var response = await taskCompletion.Task;{Environment.NewLine}");
        body.AppendLine($"return JsonConvert.DeserializeObject<{TypesHelper.GetTypeName(methodInfo.ReturnedType)}>(response.Content);");

        return Block(ParseStatement(body.ToString()));
    }

Unfortunately i did't find any points to solve this problem. This is the referense to github repo:
https://github.com/ddydeveloper/Roslyn.ApiClient.Codegen

Did anyone have such problem?


问:
Decomposing a matrix into scale, rotation, and translation with haskell
I am trying to decompose a matrix into a 3x3 rotation matrix, a scale vector, and a translation vector, using haskell. I am using the matrix from the linear package. Unfortunately, the package only exports functions for making a matrix from scale, rotation, and translation, not extracting those from a matrix. Therefore, I decided to write a function to do it myself.

However, even though I am using matrices without scaling in them, my function returns a scale vector other than V3 1.0 1.0 1.0.

```<code>import qualified Linear.Matrix     as LA
import qualified Linear.V4         as LA
import qualified Linear.V3         as LA
import qualified Linear.Vector     as LA
import qualified Linear.Quaternion as LA

import Control.Lens hiding (deep)

...

decomposeMatrix :: LA.M44 Double -> (LA.M33 Double, LA.V3 Double, LA.V3 Double)
decomposeMatrix m = (rot, scale, trans)
    where trans = (m ^.LA.column LA._w ^. LA._xyz)
          scale = LA.V3 sx sy sz
          sx    = vecLength (m ^.(LA.column LA._x) ^. LA._xyz)
          sy    = vecLength (m ^.(LA.column LA._y) ^. LA._xyz)
          sz    = vecLength (m ^.(LA.column LA._z) ^. LA._xyz)
          rot   = LA.V3 ((m ^. (LA.column LA._x) ^.LA._xyz) LA.^/ sx)
                        ((m ^. (LA.column LA._y) ^.LA._xyz) LA.^/ sy)
                        ((m ^. (LA.column LA._z) ^.LA._xyz) LA.^/ sz)

vecLength :: LA.V3 Double -> Double
vecLength (LA.V3 a b c) = sqrt (a*a + b*b + c*c)
</code>```

Here is how I am running this function in the ghci:

```<code>decomposeMatrix $ LA.mkTransformation (LA.Quaternion 1 (LA.V3 1 2 3)) $ LA.V3 1 2 3
</code>```

And this is what I get as the outcome (formatted so you can read it easier):

```<code>(V3 (V3 (-0.9259259259259259) 0.37037037037037035 7.407407407407407e-2)
    (V3 (-8.444006618414981e-2) (-0.8021806287494233) 0.5910804632890487)
    (V3 0.5965499862718936 0.5965499862718936 (-0.5368949876447042)),
V3 27.0 23.68543856465402 16.76305461424021,
V3 1.0 2.0 3.0)
</code>```

Thanks in advance.

答:
Your decomposeMatrix function seems fine (except the rotation matrix is transposed from what you want).

The big problem is your test case:  the quaternion you're using (LA.Quarternion 1 (LA.V3 1 2 3) isn't a unit quaternion, so LA.mkTransformation isn't building a pure rotation.  It's building a combination of rotation and scaling.  Try the example:

```<code>decomposeMatrix $ LA.mkTransformation (LA.axisAngle (LA.V3 1 2 3) 1)
                $ LA.V3 1 2 3
</code>```

which uses LA.axisAngle to build a unit quaternion representing a pure rotation from a vector and angle, and it will work as expected.

Body:
I am trying to decompose a matrix into a 3x3 rotation matrix, a scale vector, and a translation vector, using haskell. I am using the matrix from the linear package. Unfortunately, the package only exports functions for making a matrix from scale, rotation, and translation, not extracting those from a matrix. Therefore, I decided to write a function to do it myself.

However, even though I am using matrices without scaling in them, my function returns a scale vector other than V3 1.0 1.0 1.0.

import qualified Linear.Matrix     as LA
import qualified Linear.V4         as LA
import qualified Linear.V3         as LA
import qualified Linear.Vector     as LA
import qualified Linear.Quaternion as LA

import Control.Lens hiding (deep)

...

decomposeMatrix :: LA.M44 Double -> (LA.M33 Double, LA.V3 Double, LA.V3 Double)
decomposeMatrix m = (rot, scale, trans)
    where trans = (m ^.LA.column LA._w ^. LA._xyz)
          scale = LA.V3 sx sy sz
          sx    = vecLength (m ^.(LA.column LA._x) ^. LA._xyz)
          sy    = vecLength (m ^.(LA.column LA._y) ^. LA._xyz)
          sz    = vecLength (m ^.(LA.column LA._z) ^. LA._xyz)
          rot   = LA.V3 ((m ^. (LA.column LA._x) ^.LA._xyz) LA.^/ sx)
                        ((m ^. (LA.column LA._y) ^.LA._xyz) LA.^/ sy)
                        ((m ^. (LA.column LA._z) ^.LA._xyz) LA.^/ sz)

vecLength :: LA.V3 Double -> Double
vecLength (LA.V3 a b c) = sqrt (a*a + b*b + c*c)

Here is how I am running this function in the ghci:

decomposeMatrix $ LA.mkTransformation (LA.Quaternion 1 (LA.V3 1 2 3)) $ LA.V3 1 2 3

And this is what I get as the outcome (formatted so you can read it easier):

(V3 (V3 (-0.9259259259259259) 0.37037037037037035 7.407407407407407e-2)
    (V3 (-8.444006618414981e-2) (-0.8021806287494233) 0.5910804632890487)
    (V3 0.5965499862718936 0.5965499862718936 (-0.5368949876447042)),
V3 27.0 23.68543856465402 16.76305461424021,
V3 1.0 2.0 3.0)

Thanks in advance.

Body:
Your decomposeMatrix function seems fine (except the rotation matrix is transposed from what you want).

The big problem is your test case:  the quaternion you're using (LA.Quarternion 1 (LA.V3 1 2 3) isn't a unit quaternion, so LA.mkTransformation isn't building a pure rotation.  It's building a combination of rotation and scaling.  Try the example:

decomposeMatrix $ LA.mkTransformation (LA.axisAngle (LA.V3 1 2 3) 1)
                $ LA.V3 1 2 3

which uses LA.axisAngle to build a unit quaternion representing a pure rotation from a vector and angle, and it will work as expected.


问:
docker-entrypoint.sh: line 113: conf/neo4j.conf: Permission denied
Deploying docker Neo4J image using openshift and I'm getting this error:

```<code>docker-entrypoint.sh: line 113: conf/neo4j.conf: Permission denied.
</code>```

Any idea how to solve this issue on open shift?

答: OpenShift will by default run your image as an assigned user ID, not what your Dockerfile says to run as. You need to ensure you filesystem permissions are set so as to allow a user running with group root is able to access them, and modify as well if necessary. It will be group root as the user ID it runs as will not be in the passwd file on the container so it will fallback to using group ID of 0, corresponding to root group.

Body:
Deploying docker Neo4J image using openshift and I'm getting this error:

docker-entrypoint.sh: line 113: conf/neo4j.conf: Permission denied.

Any idea how to solve this issue on open shift?


问:
How do I get the ACTUAL CSS that was entered into a stylesheet via jQuery?
When I use jQuery to get a css property via:

$(selector).css("min-height");

The value that is returned is always a pixel value, even though I'm using "vw" units in the CSS, for example:

https://jsfiddle.net/darrengates/3yqt3nrj/

How can I get the ACTUAL CSS value (in vw) was was entered in the stylesheet?

答:
Two way you can do it.

1st (pure CSS) give a name to your CSS rule as the following so when you get the class you know what kind of CSS are applied:

```<code>.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg-red {
  background: red;
}
</code>```

2nd You can always calculate to get vh vw or % if you want:

```<code>var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');
</code>```

Note Math.ceil here because StackOverflow does not return correct px value.
(You can also check the example here: https://jsfiddle.net/dalinhuang/07s1t5qw/)

Also, you can get the raw CSS loop through style sheet but that's expansive. (REF: How to get a style attribute from a CSS class by javascript/jQuery?)

var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg_red {
  background: red;
}</code>```

```

Body:
Two way you can do it.

1st (pure CSS) give a name to your CSS rule as the following so when you get the class you know what kind of CSS are applied:

.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg-red {
  background: red;
}

2nd You can always calculate to get vh vw or % if you want:

var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');

Note Math.ceil here because StackOverflow does not return correct px value.
(You can also check the example here: https://jsfiddle.net/dalinhuang/07s1t5qw/)

Also, you can get the raw CSS loop through style sheet but that's expansive. (REF: How to get a style attribute from a CSS class by javascript/jQuery?)

var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');

.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg_red {
  background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="width_25vw min-height_25vh bg_red">
</div>


问:
Getting error: expression not assignable
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}
</code>```

答:
You aren't dereferencing the pointer properly.

At line 11:

```<code>ptr[i] = rand();
</code>```

At line 20:

```<code>if (ptr[i] > ptr[j]){
    ptr[i] = ptr[j];
}
</code>```

Alternatively you can specify *(ptr + i) to get the value at ptr[i].

Body:
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}

Body:
You aren't dereferencing the pointer properly.

At line 11:

ptr[i] = rand();

At line 20:

if (ptr[i] > ptr[j]){
    ptr[i] = ptr[j];
}

Alternatively you can specify *(ptr + i) to get the value at ptr[i].


问:
Serialize a custom transformer using python to be used within a Pyspark ML pipeline
I found the same discussion in comments section of Create a custom Transformer in PySpark ML, but there is no clear answer. There is also an unresolved JIRA corresponding to that: https://issues.apache.org/jira/browse/SPARK-17025. </p>

<p>Given that there is no option provided by Pyspark ML pipeline for saving a custom transformer written in python, what are the other options to get it done? How can I implement the _to_java method in my python class that returns a compatible java object? </p>

答:
I am not sure this is the best approach, but I too need the ability to save custom Estimators, Transformers and Models that I have created in Pyspark, and also to support their use in the Pipeline API with persistence.  Custom Pyspark Estimators, Transformers and Models may be created and used in the Pipeline API but cannot be saved.  This poses an issue in production when the model training takes longer than an event prediction cycle.

In general, Pyspark Estimators, Transformers and Models are just wrappers around the Java or Scala equivalents and the Pyspark wrappers just marshal the parameters to and from Java via py4j.  Any persisting of the model is then done on the Java side.  Because of this current structure, this limits Custom Pyspark Estimators, Transformers and Models to living only in the python world.

In a previous attempt, I was able to save a single Pyspark model by using Pickle/dill serialization.  This worked well, but still did not allow saving or loading back such from within the Pipeline API.  But, pointed to by another SO post I was directed to the OneVsRest classifier, and inspected the _to_java and _from_java methods.  They do all the heavy lifting on the Pyspark side.  After looking I thought, if one had a way to save the pickle dump to an already made and supported savable java object, then it should be possible to save a Custom Pyspark Estimator, Transformer and Model with the Pipeline API.

To that end, I found the StopWordsRemover to be the ideal object to hijack because it has an attribute, stopwords, that is a list of strings.  The dill.dumps method returns a pickled representation of the object as a string.  The plan was to turn the string into a list and then set the stopwords parameter of a StopWordsRemover to this list.  Though a list strings, I found that some of the characters would not marshal to the java object.  So the characters get converted to integers then the integers to strings.  This all works great for saving a single instance, and also when saving within in a Pipeline, because the Pipeline dutifully calls the _to_java method of my python class (we are still on the Pyspark side so this works).  But, coming back to Pyspark from java did not in the Pipeline API.

Because I am hiding my python object in a StopWordsRemover instance, the Pipeline, when coming back to Pyspark, does not know anything about my hidden class object, it knows only it has a StopWordsRemover instance.  Ideally, it would be great to subclass Pipeline and PipelineModel, but alas this brings us back to trying to serialize a Python object.  To combat this, I created a PysparkPipelineWrapper that takes a Pipeline or PipelineModel and just scans the stages, looking for a coded ID in the stopwords list (remember, this is just the pickled bytes of my python object) that tells it to unwraps the list to my instance and stores it back in the stage it came from.  Below is code that shows how this all works.

For any Custom Pyspark Estimator, Transformer and Model, just inherit from Identifiable, PysparkReaderWriter, MLReadable, MLWritable.  Then when loading a Pipeline and PipelineModel, pass such through PysparkPipelineWrapper.unwrap(pipeline).

This method does not address using the Pyspark code in Java or Scala, but at least we can save and load Custom Pyspark Estimators, Transformers and Models and work with Pipeline API.

```<code>import dill
from pyspark.ml import Transformer, Pipeline, PipelineModel
from pyspark.ml.param import Param, Params
from pyspark.ml.util import Identifiable, MLReadable, MLWritable, JavaMLReader, JavaMLWriter
from pyspark.ml.feature import StopWordsRemover
from pyspark.ml.wrapper import JavaParams
from pyspark.context import SparkContext
from pyspark.sql import Row

class PysparkObjId(object):
    """
    A class to specify constants used to idenify and setup python
    Estimators, Transformers and Models so they can be serialized on there
    own and from within a Pipline or PipelineModel.
    """
    def __init__(self):
        super(PysparkObjId, self).__init__()

    @staticmethod
    def _getPyObjId():
        return '4c1740b00d3c4ff6806a1402321572cb'

    @staticmethod
    def _getCarrierClass(javaName=False):
        return 'org.apache.spark.ml.feature.StopWordsRemover' if javaName else StopWordsRemover

class PysparkPipelineWrapper(object):
    """
    A class to facilitate converting the stages of a Pipeline or PipelineModel
    that were saved from PysparkReaderWriter.
    """
    def __init__(self):
        super(PysparkPipelineWrapper, self).__init__()

    @staticmethod
    def unwrap(pipeline):
        if not (isinstance(pipeline, Pipeline) or isinstance(pipeline, PipelineModel)):
            raise TypeError("Cannot recognize a pipeline of type %s." % type(pipeline))

        stages = pipeline.getStages() if isinstance(pipeline, Pipeline) else pipeline.stages
        for i, stage in enumerate(stages):
            if (isinstance(stage, Pipeline) or isinstance(stage, PipelineModel)):
                stages[i] = PysparkPipelineWrapper.unwrap(stage)
            if isinstance(stage, PysparkObjId._getCarrierClass()) and stage.getStopWords()[-1] == PysparkObjId._getPyObjId():
                swords = stage.getStopWords()[:-1] # strip the id
                lst = [chr(int(d)) for d in swords]
                dmp = ''.join(lst)
                py_obj = dill.loads(dmp)
                stages[i] = py_obj

        if isinstance(pipeline, Pipeline):
            pipeline.setStages(stages)
        else:
            pipeline.stages = stages
        return pipeline

class PysparkReaderWriter(object):
    """
    A mixin class so custom pyspark Estimators, Transformers and Models may
    support saving and loading directly or be saved within a Pipline or PipelineModel.
    """
    def __init__(self):
        super(PysparkReaderWriter, self).__init__()

    def write(self):
        """Returns an MLWriter instance for this ML instance."""
        return JavaMLWriter(self)

    @classmethod
    def read(cls):
        """Returns an MLReader instance for our clarrier class."""
        return JavaMLReader(PysparkObjId._getCarrierClass())

    @classmethod
    def load(cls, path):
        """Reads an ML instance from the input path, a shortcut of `read().load(path)`."""
        swr_java_obj = cls.read().load(path)
        return cls._from_java(swr_java_obj)

    @classmethod
    def _from_java(cls, java_obj):
        """
        Get the dumby the stopwords that are the characters of the dills dump plus our guid
        and convert, via dill, back to our python instance.
        """
        swords = java_obj.getStopWords()[:-1] # strip the id
        lst = [chr(int(d)) for d in swords] # convert from string integer list to bytes
        dmp = ''.join(lst)
        py_obj = dill.loads(dmp)
        return py_obj

    def _to_java(self):
        """
        Convert this instance to a dill dump, then to a list of strings with the unicode integer values of each character.
        Use this list as a set of dumby stopwords and store in a StopWordsRemover instance
        :return: Java object equivalent to this instance.
        """
        dmp = dill.dumps(self)
        pylist = [str(ord(d)) for d in dmp] # convert byes to string integer list
        pylist.append(PysparkObjId._getPyObjId()) # add our id so PysparkPipelineWrapper can id us.
        sc = SparkContext._active_spark_context
        java_class = sc._gateway.jvm.java.lang.String
        java_array = sc._gateway.new_array(java_class, len(pylist))
        for i in xrange(len(pylist)):
            java_array[i] = pylist[i]
        _java_obj = JavaParams._new_java_obj(PysparkObjId._getCarrierClass(javaName=True), self.uid)
        _java_obj.setStopWords(java_array)
        return _java_obj

class HasFake(Params):
    def __init__(self):
        super(HasFake, self).__init__()
        self.fake = Param(self, "fake", "fake param")

    def getFake(self):
        return self.getOrDefault(self.fake)

class MockTransformer(Transformer, HasFake, Identifiable):
    def __init__(self):
        super(MockTransformer, self).__init__()
        self.dataset_count = 0

    def _transform(self, dataset):
        self.dataset_count = dataset.count()
        return dataset

class MyTransformer(MockTransformer, Identifiable, PysparkReaderWriter, MLReadable, MLWritable):
    def __init__(self):
        super(MyTransformer, self).__init__()

def make_a_dataframe(sc):
    df = sc.parallelize([Row(name='Alice', age=5, height=80), Row(name='Alice', age=5, height=80), Row(name='Alice', age=10, height=80)]).toDF()
    return df

def test1():
    trA = MyTransformer()
    trA.dataset_count = 999
    print trA.dataset_count
    trA.save('test.trans')
    trB = MyTransformer.load('test.trans')
    print trB.dataset_count

def test2():
    trA = MyTransformer()
    pipeA = Pipeline(stages=[trA])
    print type(pipeA)
    pipeA.save('testA.pipe')
    pipeAA = PysparkPipelineWrapper.unwrap(Pipeline.load('testA.pipe'))
    stagesAA = pipeAA.getStages()
    trAA = stagesAA[0]
    print trAA.dataset_count

def test3():
    dfA = make_a_dataframe(sc)
    trA = MyTransformer()
    pipeA = Pipeline(stages=[trA]).fit(dfA)
    print type(pipeA)
    pipeA.save('testB.pipe')
    pipeAA = PysparkPipelineWrapper.unwrap(PipelineModel.load('testB.pipe'))
    stagesAA = pipeAA.stages
    trAA = stagesAA[0]
    print trAA.dataset_count
    dfB = pipeAA.transform(dfA)
    dfB.show()
</code>```

Body:
I found the same discussion in comments section of Create a custom Transformer in PySpark ML, but there is no clear answer. There is also an unresolved JIRA corresponding to that: https://issues.apache.org/jira/browse/SPARK-17025.

Given that there is no option provided by Pyspark ML pipeline for saving a custom transformer written in python, what are the other options to get it done? How can I implement the _to_java method in my python class that returns a compatible java object?

Body:
I am not sure this is the best approach, but I too need the ability to save custom Estimators, Transformers and Models that I have created in Pyspark, and also to support their use in the Pipeline API with persistence.  Custom Pyspark Estimators, Transformers and Models may be created and used in the Pipeline API but cannot be saved.  This poses an issue in production when the model training takes longer than an event prediction cycle.

In general, Pyspark Estimators, Transformers and Models are just wrappers around the Java or Scala equivalents and the Pyspark wrappers just marshal the parameters to and from Java via py4j.  Any persisting of the model is then done on the Java side.  Because of this current structure, this limits Custom Pyspark Estimators, Transformers and Models to living only in the python world.

In a previous attempt, I was able to save a single Pyspark model by using Pickle/dill serialization.  This worked well, but still did not allow saving or loading back such from within the Pipeline API.  But, pointed to by another SO post I was directed to the OneVsRest classifier, and inspected the _to_java and _from_java methods.  They do all the heavy lifting on the Pyspark side.  After looking I thought, if one had a way to save the pickle dump to an already made and supported savable java object, then it should be possible to save a Custom Pyspark Estimator, Transformer and Model with the Pipeline API.

To that end, I found the StopWordsRemover to be the ideal object to hijack because it has an attribute, stopwords, that is a list of strings.  The dill.dumps method returns a pickled representation of the object as a string.  The plan was to turn the string into a list and then set the stopwords parameter of a StopWordsRemover to this list.  Though a list strings, I found that some of the characters would not marshal to the java object.  So the characters get converted to integers then the integers to strings.  This all works great for saving a single instance, and also when saving within in a Pipeline, because the Pipeline dutifully calls the _to_java method of my python class (we are still on the Pyspark side so this works).  But, coming back to Pyspark from java did not in the Pipeline API.

Because I am hiding my python object in a StopWordsRemover instance, the Pipeline, when coming back to Pyspark, does not know anything about my hidden class object, it knows only it has a StopWordsRemover instance.  Ideally, it would be great to subclass Pipeline and PipelineModel, but alas this brings us back to trying to serialize a Python object.  To combat this, I created a PysparkPipelineWrapper that takes a Pipeline or PipelineModel and just scans the stages, looking for a coded ID in the stopwords list (remember, this is just the pickled bytes of my python object) that tells it to unwraps the list to my instance and stores it back in the stage it came from.  Below is code that shows how this all works.

For any Custom Pyspark Estimator, Transformer and Model, just inherit from Identifiable, PysparkReaderWriter, MLReadable, MLWritable.  Then when loading a Pipeline and PipelineModel, pass such through PysparkPipelineWrapper.unwrap(pipeline).

This method does not address using the Pyspark code in Java or Scala, but at least we can save and load Custom Pyspark Estimators, Transformers and Models and work with Pipeline API.

import dill
from pyspark.ml import Transformer, Pipeline, PipelineModel
from pyspark.ml.param import Param, Params
from pyspark.ml.util import Identifiable, MLReadable, MLWritable, JavaMLReader, JavaMLWriter
from pyspark.ml.feature import StopWordsRemover
from pyspark.ml.wrapper import JavaParams
from pyspark.context import SparkContext
from pyspark.sql import Row

class PysparkObjId(object):
    """
    A class to specify constants used to idenify and setup python
    Estimators, Transformers and Models so they can be serialized on there
    own and from within a Pipline or PipelineModel.
    """
    def __init__(self):
        super(PysparkObjId, self).__init__()

    @staticmethod
    def _getPyObjId():
        return '4c1740b00d3c4ff6806a1402321572cb'

    @staticmethod
    def _getCarrierClass(javaName=False):
        return 'org.apache.spark.ml.feature.StopWordsRemover' if javaName else StopWordsRemover

class PysparkPipelineWrapper(object):
    """
    A class to facilitate converting the stages of a Pipeline or PipelineModel
    that were saved from PysparkReaderWriter.
    """
    def __init__(self):
        super(PysparkPipelineWrapper, self).__init__()

    @staticmethod
    def unwrap(pipeline):
        if not (isinstance(pipeline, Pipeline) or isinstance(pipeline, PipelineModel)):
            raise TypeError("Cannot recognize a pipeline of type %s." % type(pipeline))

        stages = pipeline.getStages() if isinstance(pipeline, Pipeline) else pipeline.stages
        for i, stage in enumerate(stages):
            if (isinstance(stage, Pipeline) or isinstance(stage, PipelineModel)):
                stages[i] = PysparkPipelineWrapper.unwrap(stage)
            if isinstance(stage, PysparkObjId._getCarrierClass()) and stage.getStopWords()[-1] == PysparkObjId._getPyObjId():
                swords = stage.getStopWords()[:-1] # strip the id
                lst = [chr(int(d)) for d in swords]
                dmp = ''.join(lst)
                py_obj = dill.loads(dmp)
                stages[i] = py_obj

        if isinstance(pipeline, Pipeline):
            pipeline.setStages(stages)
        else:
            pipeline.stages = stages
        return pipeline

class PysparkReaderWriter(object):
    """
    A mixin class so custom pyspark Estimators, Transformers and Models may
    support saving and loading directly or be saved within a Pipline or PipelineModel.
    """
    def __init__(self):
        super(PysparkReaderWriter, self).__init__()

    def write(self):
        """Returns an MLWriter instance for this ML instance."""
        return JavaMLWriter(self)

    @classmethod
    def read(cls):
        """Returns an MLReader instance for our clarrier class."""
        return JavaMLReader(PysparkObjId._getCarrierClass())

    @classmethod
    def load(cls, path):
        """Reads an ML instance from the input path, a shortcut of `read().load(path)`."""
        swr_java_obj = cls.read().load(path)
        return cls._from_java(swr_java_obj)

    @classmethod
    def _from_java(cls, java_obj):
        """
        Get the dumby the stopwords that are the characters of the dills dump plus our guid
        and convert, via dill, back to our python instance.
        """
        swords = java_obj.getStopWords()[:-1] # strip the id
        lst = [chr(int(d)) for d in swords] # convert from string integer list to bytes
        dmp = ''.join(lst)
        py_obj = dill.loads(dmp)
        return py_obj

    def _to_java(self):
        """
        Convert this instance to a dill dump, then to a list of strings with the unicode integer values of each character.
        Use this list as a set of dumby stopwords and store in a StopWordsRemover instance
        :return: Java object equivalent to this instance.
        """
        dmp = dill.dumps(self)
        pylist = [str(ord(d)) for d in dmp] # convert byes to string integer list
        pylist.append(PysparkObjId._getPyObjId()) # add our id so PysparkPipelineWrapper can id us.
        sc = SparkContext._active_spark_context
        java_class = sc._gateway.jvm.java.lang.String
        java_array = sc._gateway.new_array(java_class, len(pylist))
        for i in xrange(len(pylist)):
            java_array[i] = pylist[i]
        _java_obj = JavaParams._new_java_obj(PysparkObjId._getCarrierClass(javaName=True), self.uid)
        _java_obj.setStopWords(java_array)
        return _java_obj

class HasFake(Params):
    def __init__(self):
        super(HasFake, self).__init__()
        self.fake = Param(self, "fake", "fake param")

    def getFake(self):
        return self.getOrDefault(self.fake)

class MockTransformer(Transformer, HasFake, Identifiable):
    def __init__(self):
        super(MockTransformer, self).__init__()
        self.dataset_count = 0

    def _transform(self, dataset):
        self.dataset_count = dataset.count()
        return dataset

class MyTransformer(MockTransformer, Identifiable, PysparkReaderWriter, MLReadable, MLWritable):
    def __init__(self):
        super(MyTransformer, self).__init__()

def make_a_dataframe(sc):
    df = sc.parallelize([Row(name='Alice', age=5, height=80), Row(name='Alice', age=5, height=80), Row(name='Alice', age=10, height=80)]).toDF()
    return df

def test1():
    trA = MyTransformer()
    trA.dataset_count = 999
    print trA.dataset_count
    trA.save('test.trans')
    trB = MyTransformer.load('test.trans')
    print trB.dataset_count

def test2():
    trA = MyTransformer()
    pipeA = Pipeline(stages=[trA])
    print type(pipeA)
    pipeA.save('testA.pipe')
    pipeAA = PysparkPipelineWrapper.unwrap(Pipeline.load('testA.pipe'))
    stagesAA = pipeAA.getStages()
    trAA = stagesAA[0]
    print trAA.dataset_count

def test3():
    dfA = make_a_dataframe(sc)
    trA = MyTransformer()
    pipeA = Pipeline(stages=[trA]).fit(dfA)
    print type(pipeA)
    pipeA.save('testB.pipe')
    pipeAA = PysparkPipelineWrapper.unwrap(PipelineModel.load('testB.pipe'))
    stagesAA = pipeAA.stages
    trAA = stagesAA[0]
    print trAA.dataset_count
    dfB = pipeAA.transform(dfA)
    dfB.show()


问:
Starting second javascript when the first one is finished
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:  </p>

```<code>HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:
<script>
function move() {
    var elem = document.getElementById("myBar");
    var myFunc01 = function() {
    var i = 1;
    while (i < 101) {
        (function(i) {
            setTimeout(function() {
                i++;
                elem.style.width = i + '%';
                elem.innerHTML = i + '%';
            }, 600 * i)
        })(i++)
    }
    };
    myFunc01();
}
</script>
<script>
function finalize() {
    var elem = document.getElementById("myBar");
    var myFunc02 = function() {
                elem.innerHTML = 'Finalizing...';
    };
    setTimeout(myFunc02, 600);
}
</script>
</code>```

答:
You could use a callback. A callback is a function that runs upon completion.

```<code>function move(callback) {
    //code you want to happen first
}
move(function(){
    //code you want to have happen after completion
})
</code>```

thats the basic idea of how a simple callback works

Body:
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:

HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:

Body:
You could use a callback. A callback is a function that runs upon completion.

function move(callback) {
    //code you want to happen first
}
move(function(){
    //code you want to have happen after completion
})

thats the basic idea of how a simple callback works