问:
Android Studio : display date got from another activity
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

```<code>int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);
</code>```

and then put it in a string using something like

```<code>String strcal01 = sdf.format(new calendrier);
</code>```

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.

答:
Use calendrier.getTime() instead of new calendrier

Your mistake:

The method format is expecting an object of the type Date, You are trying to pass the type Calendar. Also FYI, you have used the new keyword wrongly.

Body:
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);

and then put it in a string using something like

String strcal01 = sdf.format(new calendrier);

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.


来源: stackexchange

问:
matplotlib render image with specs (size, alligment etc.) in pixels
I have specs for a mockup, for example, Photoshop/Illustrator/Sketch file with each elements specifications like size, position, and coordinates in pixels.

An image looks like:

I can draw similar image just using standard matplotlib technic without any problems.

The question is, how to render an image exactly with its specs? All sizes, font sizes, alignments, should be the same as in the specs (as it's drawn in Illustrator).

I've researched over matplotlib docs, but even transformers tutorial doesn't help.

Update with an exact example.

I have a mock at Zeplin which shows coordinated of each plot (Image is also a plot here). So I know, that the image has margins 25x25px from a border and its size is 80x80 pixels.

this is mock image (again not allowed to embed the image).

How would you do that?

The code I use for drawing

```<code>fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharey=True)

recs = ax[0].barh(y_pos, widths, align='edge');

img = mpimg.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')

ax[0].spines['left'].set_visible(False);
ax[0].spines['right'].set_visible(False);
ax[0].spines['bottom'].set_visible(False);
ax[0].spines['top'].set_visible(False);

ax[0].get_xaxis().set_visible(True);
ax[0].get_yaxis().set_visible(True);

obj = ax[0].text(x=0, y=3.9, s=r'Name: Vitaly Davydov',
          fontsize=30, fontname="Courier New", weight='bold');

ax[0].axhline(y=3.85, xmin=0, xmax=0.75, color='black');

# I'd like to place axicon exactly with 25x25 marging from top left corner
axicon = fig.add_axes([0.08, 1, 0.2, 0.2], transform=None)
axicon.axis('off');
axicon.imshow(img, interpolation='none');

for i, r in enumerate(recs):
    r.set_color(index_to_color[i]);
    r.set_height(col_wight);
    ax[0].text(x=0, y=text_positions[i], s=index_to_text[i], fontsize=30, fontname="Courier New");

ax[1].spines['left'].set_visible(False);
ax[1].spines['right'].set_visible(False);
ax[1].spines['bottom'].set_visible(False);
ax[1].spines['top'].set_visible(False);

ax[1].get_xaxis().set_visible(False);
ax[1].get_yaxis().set_visible(False);

ax[1].text(x=0, y=3.9, s='Increment:', fontsize=30,
           fontname="Courier New", weight='bold');

ax[1].axhline(y=3.85, xmin=0, xmax=0.4, color='black');

for i, r in enumerate(recs):
    text_x, text_y = r.xy

    increment_pos_y = text_y + col_wight / 2
    if increment_values[i] > 0:
        increment_text = '+{}'.format(increment_values[i])
    elif increment_values[i] < 0:
        increment_text = '-{}'.format(increment_values[i])
    else:
        increment_text = '{}'.format(increment_values[i])

    ax[1].text(x=0, y=increment_pos_y, s=increment_text,
               fontsize=30, color=index_to_color[i],
               fontname="Courier New", weight='bold');
</code>```

In this example I'd like to place axicon axes that is an image with 25x25 margin and 80x80 size (all in pixels).

答:
To place an axes to the figure, you can use fig.add_axes([left, bottom, width, height]), where left, bottom, width, height are fractions of the figure size.

To convert from pixels to fraction of figure size, you need to divide the pixels by the figure dpi and the figure size. E.g. for the left edge

```<code>left = 25/fig.dpi/fig.get_size_inches()[0]
</code>```

Complete example:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, figsize=(10, 7))
y_pos, widths = np.linspace(0,3,4), np.random.rand(4)
recs = ax[0].barh(y_pos, widths, align='edge');

#img = plt.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')
img = np.random.rand(80,80)

# I'd like to place axicon exactly with 25x25 marging from top left corner
x,y= 25,25 #pixels
dx,dy = 80,80
w,h = fig.get_size_inches()
axicon = fig.add_axes([x/float(fig.dpi)/w, 1.-(y+dy)/float(fig.dpi)/h,
                       dx/float(fig.dpi)/w, dy/float(fig.dpi)/h])
axicon.axis('off');
axicon.imshow(img, interpolation='none');

plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have specs for a mockup, for example, Photoshop/Illustrator/Sketch file with each elements specifications like size, position, and coordinates in pixels.

An image looks like:

I can draw similar image just using standard matplotlib technic without any problems.

The question is, how to render an image exactly with its specs? All sizes, font sizes, alignments, should be the same as in the specs (as it's drawn in Illustrator).

I've researched over matplotlib docs, but even transformers tutorial doesn't help.

Update with an exact example.

I have a mock at Zeplin which shows coordinated of each plot (Image is also a plot here). So I know, that the image has margins 25x25px from a border and its size is 80x80 pixels.

this is mock image (again not allowed to embed the image).

How would you do that?

The code I use for drawing

fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharey=True)

recs = ax[0].barh(y_pos, widths, align='edge');

img = mpimg.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')

ax[0].spines['left'].set_visible(False);
ax[0].spines['right'].set_visible(False);
ax[0].spines['bottom'].set_visible(False);
ax[0].spines['top'].set_visible(False);

ax[0].get_xaxis().set_visible(True);
ax[0].get_yaxis().set_visible(True);

obj = ax[0].text(x=0, y=3.9, s=r'Name: Vitaly Davydov',
          fontsize=30, fontname="Courier New", weight='bold');

ax[0].axhline(y=3.85, xmin=0, xmax=0.75, color='black');

# I'd like to place axicon exactly with 25x25 marging from top left corner
axicon = fig.add_axes([0.08, 1, 0.2, 0.2], transform=None)
axicon.axis('off');
axicon.imshow(img, interpolation='none');

for i, r in enumerate(recs):
    r.set_color(index_to_color[i]);
    r.set_height(col_wight);
    ax[0].text(x=0, y=text_positions[i], s=index_to_text[i], fontsize=30, fontname="Courier New");

ax[1].spines['left'].set_visible(False);
ax[1].spines['right'].set_visible(False);
ax[1].spines['bottom'].set_visible(False);
ax[1].spines['top'].set_visible(False);

ax[1].get_xaxis().set_visible(False);
ax[1].get_yaxis().set_visible(False);

ax[1].text(x=0, y=3.9, s='Increment:', fontsize=30,
           fontname="Courier New", weight='bold');

ax[1].axhline(y=3.85, xmin=0, xmax=0.4, color='black');

for i, r in enumerate(recs):
    text_x, text_y = r.xy

    increment_pos_y = text_y + col_wight / 2
    if increment_values[i] > 0:
        increment_text = '+{}'.format(increment_values[i])
    elif increment_values[i] < 0:
        increment_text = '-{}'.format(increment_values[i])
    else:
        increment_text = '{}'.format(increment_values[i])

    ax[1].text(x=0, y=increment_pos_y, s=increment_text,
               fontsize=30, color=index_to_color[i],
               fontname="Courier New", weight='bold');

In this example I'd like to place axicon axes that is an image with 25x25 margin and 80x80 size (all in pixels).

Body:
To place an axes to the figure, you can use fig.add_axes([left, bottom, width, height]), where left, bottom, width, height are fractions of the figure size.

To convert from pixels to fraction of figure size, you need to divide the pixels by the figure dpi and the figure size. E.g. for the left edge

left = 25/fig.dpi/fig.get_size_inches()[0]

Complete example:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, figsize=(10, 7))
y_pos, widths = np.linspace(0,3,4), np.random.rand(4)
recs = ax[0].barh(y_pos, widths, align='edge');

#img = plt.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')
img = np.random.rand(80,80)

# I'd like to place axicon exactly with 25x25 marging from top left corner
x,y= 25,25 #pixels
dx,dy = 80,80
w,h = fig.get_size_inches()
axicon = fig.add_axes([x/float(fig.dpi)/w, 1.-(y+dy)/float(fig.dpi)/h,
                       dx/float(fig.dpi)/w, dy/float(fig.dpi)/h])
axicon.axis('off');
axicon.imshow(img, interpolation='none');

plt.show()


问:
Getting "The error was: AttributeError: 'module' object has no attribute 'exceptions'" while using json_query
I'm trying to extract key, value from list of dictionary using json_query filter but getting an error. Below is the playbook

```<code>  1
  2 - name: test
  3   hosts: localhost
  4   vars:
  5           testList: [ { "key1": "value11", "key2": "value12", "key3": "value13" },
  6                       { "key1": "value21", "key2": "value22", "key3": "value23" },
  7                       { "key1": "value31", "key2": "value32", "key3": "value33" } ]
  8   tasks:
  9        - name: Getting keys
 10          debug:
 11            msg: "{{ testList | json_query('[*].{key1: key1 , key2: key2}')}}"
</code>```

Here is the output

```<code> [WARNING]: No inventory was parsed, only implicit localhost is available

 [WARNING]: Could not match supplied host pattern, ignoring: all

 [WARNING]: provided hosts list is empty, only localhost is available

PLAY [test] ****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [Getting keys] ********************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'exceptions'
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}

PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1
</code>```

With a single key it's working fine "{{ testList | json_query('[*].key1')}}"

Referring the document http://docs.ansible.com/ansible/latest/playbooks_filters.html#json-query-filter

Is there any other filter to get multiple key, value from list of dictionaries?

答:
Upgrade to the latest Ansible version.

This error happens for example on 2.1.3.0 (although you might be using a different version judging from the phrase in one of the warnings).

Here is the result on current version 2.4.1.0:

```<code>TASK [Getting keys] *****************************************************************************************************
Unaltered: {'msg': [{'key2': u'value12', 'key1': u'value11'}, {'key2': u'value22', 'key1': u'value21'}, {'key2': u'value32', 'key1': u'value31'}]}
ok: [localhost] => {
    "msg": [
        {
            "key1": "value11",
            "key2": "value12"
        },
        {
            "key1": "value21",
            "key2": "value22"
        },
        {
            "key1": "value31",
            "key2": "value32"
        }
    ]
}
</code>```

Body:
I'm trying to extract key, value from list of dictionary using json_query filter but getting an error. Below is the playbook

  1
  2 - name: test
  3   hosts: localhost
  4   vars:
  5           testList: [ { "key1": "value11", "key2": "value12", "key3": "value13" },
  6                       { "key1": "value21", "key2": "value22", "key3": "value23" },
  7                       { "key1": "value31", "key2": "value32", "key3": "value33" } ]
  8   tasks:
  9        - name: Getting keys
 10          debug:
 11            msg: "{{ testList | json_query('[*].{key1: key1 , key2: key2}')}}"

Here is the output

 [WARNING]: No inventory was parsed, only implicit localhost is available

 [WARNING]: Could not match supplied host pattern, ignoring: all

 [WARNING]: provided hosts list is empty, only localhost is available

PLAY [test] ****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [Getting keys] ********************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'exceptions'
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}

PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

With a single key it's working fine "{{ testList | json_query('[*].key1')}}"

Referring the document http://docs.ansible.com/ansible/latest/playbooks_filters.html#json-query-filter

Is there any other filter to get multiple key, value from list of dictionaries?

Body:
Upgrade to the latest Ansible version.

This error happens for example on 2.1.3.0 (although you might be using a different version judging from the phrase in one of the warnings).

Here is the result on current version 2.4.1.0:

TASK [Getting keys] *****************************************************************************************************
Unaltered: {'msg': [{'key2': u'value12', 'key1': u'value11'}, {'key2': u'value22', 'key1': u'value21'}, {'key2': u'value32', 'key1': u'value31'}]}
ok: [localhost] => {
    "msg": [
        {
            "key1": "value11",
            "key2": "value12"
        },
        {
            "key1": "value21",
            "key2": "value22"
        },
        {
            "key1": "value31",
            "key2": "value32"
        }
    ]
}


问:
How to change views in android
Consider we have two Activies: Activity A and Activity B, both have an ImageView. If we click on ImageView in Activity A, ImageView in Activity B should change to another image. Please tell us, how to achieve this by using interface

Your timely suggestions will help us a lot

答: As i understand what you are asking for has been asked many times. Its how to send data between activities. Here is an answer from another thread. Also you can check the Android documentation and read about bundles. </p>

Title: How to change views in android


问:
Trying to use a number with percentage as value
Hi there I am trying to run a loop that changes the value of all cells containing 0% to value "N/A". I wrote the following code: </p>

```<code>Dim Fail As Integer
Fail = "0%"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X
</code>```

<p>but all it does is that it replaces all the values in column G with "N/A". Where did I go wrong? </p>

答:
Use simple replace statement on your range.</p>

```<code>Worksheets("Summary").Range("G22:G1000").Replace What:="0%", Replacement:="NA"
</code>```

Body:
Hi there I am trying to run a loop that changes the value of all cells containing 0% to value "N/A". I wrote the following code:

Dim Fail As Integer
Fail = "0%"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X

but all it does is that it replaces all the values in column G with "N/A". Where did I go wrong?

Body:
Use simple replace statement on your range.

Worksheets("Summary").Range("G22:G1000").Replace What:="0%", Replacement:="NA"


问:
FFmpeg forward iptv .ts remote stream returned (401 Unauthorized authorization failed)
My problem is when i try to forward remote iptv channel .ts file from remote server using this command

Local Windows :

```<code>ffmpeg -i http://ip_tv_server.com:_port_/live/user/user/ts_file.ts -vcodec libx264 -vb 500k -vprofile baseline -level 2.1 -acodec aac -ab 64000 -ar 48000 -ac 2 -strict experimental -f flv rtmp://my_rtmp_server:1935/live/myStream -tune zerolatency
</code>```

it works fine and start sending streaming to my server (red5-server) .

but when i use the same command in my linux vps (Ubuntu 14.04) i get this error from ffmpeg :

```<code>http://ip_tv_server.com:_port_/live/user/user/ts_file.ts: Server returned 401 Unauthorized (authorization failed)
</code>```

do i need to use custom http headers ?

and why it's working on my local windows and not in vps (ubuntu 14.04-x64) ?

答:
The error message generally means that you are trying to access something or perform some action on a server, and the server requires you to login or be be authorised to do it.

Generally this would be associated with a HTTP request and user name and password and/or a user session. The authorisation might even be as simple as checking a cookie on your local machine. This is one example of an authorisation which might work on one machine but not another.

The authorisation mechanism could also be much more involved or use some completely different logic - for example the server may have a GEO blocking mechanism and your local machine is on a network it considers to be ok while the VPS is not.

There server may even have a mechanism to limit concurrent devices or concurrent streams and accessing the same stream from two devices could trigger this.

Body:
My problem is when i try to forward remote iptv channel .ts file from remote server using this command

Local Windows :

ffmpeg -i http://ip_tv_server.com:_port_/live/user/user/ts_file.ts -vcodec libx264 -vb 500k -vprofile baseline -level 2.1 -acodec aac -ab 64000 -ar 48000 -ac 2 -strict experimental -f flv rtmp://my_rtmp_server:1935/live/myStream -tune zerolatency

it works fine and start sending streaming to my server (red5-server) .

but when i use the same command in my linux vps (Ubuntu 14.04) i get this error from ffmpeg :

http://ip_tv_server.com:_port_/live/user/user/ts_file.ts: Server returned 401 Unauthorized (authorization failed)

do i need to use custom http headers ?

and why it's working on my local windows and not in vps (ubuntu 14.04-x64) ?


问:
C# - How to Italicise a words within a string resource
I'm writing a WPF application and I need to italicise words within descriptions on my view while still having them within resources to provide multi-lingual support later on. These descriptions are resourced and pass through a director that matches the descriptions in the view model by their code to their appropriate placement.

What I have tried:

I've begun resourcing the words of importance separately and added placeholder codes within the description resources. I then wanted to insert the words of importance into the description strings as they pass through the director but I can't italicise them at this stage either as they're just strings! How can i do achieve this?

答:
If you have an entire description as one string presented in f.e. a label, and you only want one part of this string italic, then this is not possible.

In case of a label (not sure what control is presenting your descriptions) you can create a seperated label for this important word, and place this specific label (with the italic property set) where you want it to be.


问:
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?
views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse
import random
import hashlib
import os
import requests

def index(request):
 """Displays the page that asks for the phone number"""
 return render(request, "verify/sms.html")

def verify(request):
 """Displays the page that asks for the verification code"""
 # if the form wasn't submitted properly, then go to index page
 try:
    phoneNumber = request.POST['phonenumber']
 except:
    return render(request, "verify/sms.html")

 verificationCode = str(random.randint(1000000, 9999999))

# the check sequence is sent to the next page to verify if the code entered is correct
 checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest()

 sendVerificationCode(phoneNumber, verificationCode)
 return render(request, "verify/verification.html", {"code": checkSequence})

def checkCode(request):
"""Checks if the verification code entered is correct"""
 try:
    verificationCode = request.GET['verification']
    correctCheckSequence = request.GET['code']
 except:
    return render(request, "verify/sms.html")

# check the correct check sequence against the check sequence based on the verification code provided
 checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest()
 if checkSequence == correctCheckSequence:
    return HttpResponse("1")
 else:
    return HttpResponse("0")

def sendVerificationCode(phoneNumber, verificationCode):
"""Sends the verification code to the provided phone number using TILL API"""
 if len(phoneNumber) < 10:
    return              # doesn't give the user an error message - just doesn't send the message

 TILL_URL = os.environ.get("TILL_URL")
requests.post(TILL_URL, json={"phone":[phoneNumber], "text": "Verication code: " + str(verificationCode)})
</code>```

urls.py

```<code>from django.conf.urls import url, include
from . import views

urlpatterns = [
 url(r'^$', views.index, name="index"),
 url(r'^verify/$', views.verify, name="verify"),
 url(r'^checkCode/$', views.checkCode, name="checkCode")
]
</code>```

models.py

```<code>from django.db import models
</code>```

admin.py

```<code>from django.contrib import admin
</code>```

apps.py

```<code>from django.apps import AppConfig

class VerifyConfig(AppConfig):
 name = 'verify'
</code>```

Creating a sms-validation app.Where a user enters his phone number and message is send to validate his number.

Soon after asking his number and hitting enter it shows error.

raise MissingSchema(error)
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?

Traceback

```<code>Internal Server Error: /verify/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tushar/Downloads/sms-verify-master/verify/views.py", line 25, in verify
sendVerificationCode(phoneNumber, verificationCode)
File "/home/tushar/Downloads/sms-verify-master/verify/views.py", line 49, in sendVerificationCode
requests.post(TILL_URL, json={"phone":[phoneNumber], "text": "Verication code: " + str(verificationCode)})
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 109, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 454, in request
prep = self.prepare_request(req)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 388, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 293, in prepare
self.prepare_url(url, params)
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 353, in prepare_url
raise MissingSchema(error)
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?
</code>```

答:
TILL_URL is 'None'

Either change this line:

```<code>TILL_URL = os.environ.get("TILL_URL")
</code>```

To:

```<code>TILL_URL = "https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>"
</code>```

or set TILL_URL environment variable in your OS, by export command in linux terminal:

```<code>~ export TILL_URL="https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>"
</code>```

They API http:

```<code>https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>
</code>```

Use your user name and API key from your dashboard, which you get after registering:

https://platform.tillmobile.com/dashboard/

Body:
views.py

from django.shortcuts import render
from django.http import HttpResponse
import random
import hashlib
import os
import requests

def index(request):
 """Displays the page that asks for the phone number"""
 return render(request, "verify/sms.html")

def verify(request):
 """Displays the page that asks for the verification code"""
 # if the form wasn't submitted properly, then go to index page
 try:
    phoneNumber = request.POST['phonenumber']
 except:
    return render(request, "verify/sms.html")

 verificationCode = str(random.randint(1000000, 9999999))

# the check sequence is sent to the next page to verify if the code entered is correct
 checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest()

 sendVerificationCode(phoneNumber, verificationCode)
 return render(request, "verify/verification.html", {"code": checkSequence})

def checkCode(request):
"""Checks if the verification code entered is correct"""
 try:
    verificationCode = request.GET['verification']
    correctCheckSequence = request.GET['code']
 except:
    return render(request, "verify/sms.html")

# check the correct check sequence against the check sequence based on the verification code provided
 checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest()
 if checkSequence == correctCheckSequence:
    return HttpResponse("1")
 else:
    return HttpResponse("0")

def sendVerificationCode(phoneNumber, verificationCode):
"""Sends the verification code to the provided phone number using TILL API"""
 if len(phoneNumber) < 10:
    return              # doesn't give the user an error message - just doesn't send the message

 TILL_URL = os.environ.get("TILL_URL")
requests.post(TILL_URL, json={"phone":[phoneNumber], "text": "Verication code: " + str(verificationCode)})

urls.py

from django.conf.urls import url, include
from . import views

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

models.py

from django.db import models

admin.py

from django.contrib import admin

apps.py

from django.apps import AppConfig

class VerifyConfig(AppConfig):
 name = 'verify'

Creating a sms-validation app.Where a user enters his phone number and message is send to validate his number.

Soon after asking his number and hitting enter it shows error.

raise MissingSchema(error)
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?

Traceback

Internal Server Error: /verify/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-
packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tushar/Downloads/sms-verify-master/verify/views.py", line 25, in verify
sendVerificationCode(phoneNumber, verificationCode)
File "/home/tushar/Downloads/sms-verify-master/verify/views.py", line 49, in sendVerificationCode
requests.post(TILL_URL, json={"phone":[phoneNumber], "text": "Verication code: " + str(verificationCode)})
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 109, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 454, in request
prep = self.prepare_request(req)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 388, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 293, in prepare
self.prepare_url(url, params)
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 353, in prepare_url
raise MissingSchema(error)
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?

Body:
TILL_URL is 'None'

Either change this line:

TILL_URL = os.environ.get("TILL_URL")

To:

TILL_URL = "https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>"

or set TILL_URL environment variable in your OS, by export command in linux terminal:

~ export TILL_URL="https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>"

They API http:

https://platform.tillmobile.com/api/send/?username=<username>&api_key=<api_key>

Use your user name and API key from your dashboard, which you get after registering:

https://platform.tillmobile.com/dashboard/


问:
Get all values related to id (ASP.NET MVC)
I have two tables Patients and appointments.

Here is model of patients

```<code> public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}
</code>```

Here is Appointment model

```<code> public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}
</code>```

Also I have table to connect patient with appointments (because of one patient may have several appointments)

```<code>public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}
</code>```

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

```<code>  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });
</code>```

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

答:
To avoid the error noted in the comments

Severity Code Description Project File Line Suppression State Error
  CS0029 Cannot implicitly convert type '' to
  'int?' RS_Main
  C:\Users\nemes\Source\Repos\RIS_Project_New\RS_Main\Controllers\PatientDatabaseController.cs
  43 Active

you need to remove that new {} inside the select:

```<code> var id = ctx.Patients.Where(x => x.Name == name).Select(x=> x.Id);
</code>```

with the new { ...}  you are returning an anonymous type and not the int.

Body:
I have two tables Patients and appointments.

Here is model of patients

 public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}

Here is Appointment model

 public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}

Also I have table to connect patient with appointments (because of one patient may have several appointments)

public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

Body:
To avoid the error noted in the comments

Severity Code Description Project File Line Suppression State Error
  CS0029 Cannot implicitly convert type '' to
  'int?' RS_Main
  C:\Users\nemes\Source\Repos\RIS_Project_New\RS_Main\Controllers\PatientDatabaseController.cs
  43 Active

you need to remove that new {} inside the select:

 var id = ctx.Patients.Where(x => x.Name == name).Select(x=> x.Id);

with the new { ...}  you are returning an anonymous type and not the int.


问:
Checkbox in MVC 5 ASP.net
I made a "Availability" option in my database, this is set as a "bit". When I made a controller on my generated model, it came out as a dropdownlist with 2 values: true and false. I don't want this to be a dropdown list but a checkbox. I've googled all around and couldnt find an easy fix for this. Any of you have an idea how to do this? My code looks like this:</p>

```<code><div class="form-group">
        @Html.LabelFor(model => model.Beschikbaar, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.Beschikbaar)
                @Html.ValidationMessageFor(model => model.Beschikbaar, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
</code>```

答:
Use this

```<code><input type="checkbox" name="Beschikbaar" value="true" data-val="true" data-val-required="The Beschikbaarfield is required."/>
</code>```

in place of the line

```<code>@Html.EditorFor(model => model.Beschikbaar)
</code>```

Title: Checkbox in MVC 5 ASP.net

Body:
I made a "Availability" option in my database, this is set as a "bit". When I made a controller on my generated model, it came out as a dropdownlist with 2 values: true and false. I don't want this to be a dropdown list but a checkbox. I've googled all around and couldnt find an easy fix for this. Any of you have an idea how to do this? My code looks like this:

        @Html.LabelFor(model => model.Beschikbaar, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Beschikbaar)
                @Html.ValidationMessageFor(model => model.Beschikbaar, "", new { @class = "text-danger" })

Body:
Use this

<input type="checkbox" name="Beschikbaar" value="true" data-val="true" data-val-required="The Beschikbaarfield is required."/>

in place of the line

@Html.EditorFor(model => model.Beschikbaar)


问:
How can I console.log the selected option from angular Material form and table? ANGULAR 4
I have a table that I made with Angular Material. It contains some data made as an object in the ts file. See the code below:

```<code>import {Component} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html',
  styleUrls: ['./accounts.component.sass']
})

export class AccountsComponent {
  displayedColumns = ['Account Number', 'Account Name', 'Acctype1', 'Acctype2', 'Acctype3'];
  dataSource = new ExampleDataSource()

  acctypes = [
  {value: 'Tax', viewValue: 'Tax'},
  {value: 'Liabilities', viewValue: 'Liabilities'},
  {value: 'Enable', viewValue: 'Enable'},
  {value: 'Income Statement', viewValue: 'Income Statement'}
 ];

 onSelect(){
   console.log(DataSource)
 }
}

export interface Element {
  AccountNumber: string;
  AccountName: string;
  Acctype1: string;
  Acctype2: string;
  Acctype3: string;
}

const data: Element[] = [
  {AccountNumber: '001' , AccountName: 'Pepsi', Acctype1: 'H', Acctype2: 'D', Acctype3: 'P'},
  { AccountNumber: '002', AccountName: 'Coke', Acctype1: 'He', Acctype2: 'G', Acctype3: 'Wm'},
  { AccountNumber: '003', AccountName: 'Fanta', Acctype1: 'Li', Acctype2: 'Dk', Acctype3: 'R'},
  { AccountNumber: '004', AccountName: 'Faxe Kondi', Acctype1: 'Be', Acctype2: 'B', Acctype3: 'K'},
  { AccountNumber: '005', AccountName: 'Dr Pepper', Acctype1: 'B', Acctype2: 'Pn', Acctype3: 'M'},
  { AccountNumber: '006', AccountName: 'Mars', Acctype1: 'C', Acctype2: 'Mw', Acctype3: 'Xnm'},
  { AccountNumber: '007', AccountName: 'Snickers', Acctype1: 'N', Acctype2: 'D', Acctype3: 'P'},
  { AccountNumber: '008', AccountName: 'Converse', Acctype1: 'O', Acctype2: 'Z', Acctype3: 'Wc'},
  { AccountNumber: '009', AccountName: 'Adidas', Acctype1: 'F', Acctype2: 'Q', Acctype3: 'O'},
  { AccountNumber: '010', AccountName: 'Nike', Acctype1: 'Ne', Acctype2: 'Z', Acctype3: 'B'},

];

export class ExampleDataSource extends DataSource<any> {

  connect(): Observable<Element[]> {
    return Observable.of(data);
  }
  disconnect() {}
}
</code>```

What I want to do is console.log all the data from the table and dropdown menu. Currently, when I select an option, the console logs

```<code>ƒ DataSource() {
    }
</code>```

which obviously isn't what I need.

What am I doing wrong? This is the relevant HTML for the table:

```<code><div id='table-container'>
  <form id='accForm'>
  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="Account Number">
      <mat-header-cell *matHeaderCellDef> Account Number </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.AccountNumber}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Account Name">
      <mat-header-cell *matHeaderCellDef> Account Name </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.AccountName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype1">
      <mat-header-cell *matHeaderCellDef> 2016/17 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element" id="accType">
          <mat-form-field>
            <mat-select name= 'acctype_id' [(ngModel)]="element.accType1" (change)="onSelect()" placeholder="Select Type">
              <mat-option *ngFor="let acctype of acctypes" [value]="acctype.value">
                {{ acctype.viewValue }}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype2">
      <mat-header-cell *matHeaderCellDef> 2015/16 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.Acctype2}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype3">
      <mat-header-cell *matHeaderCellDef> 2014/15 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.Acctype3}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
  </form>
</div>
</code>```

I've been stuck on this for days, any help would be appreciated

答:
You need to pass element as an argument in the onSelect method:

```<code><mat-select name= 'acctype_id' [(ngModel)]="element.accType1" (change)="onSelect(element)" placeholder="Select Type">
    <mat-option *ngFor="let acctype of acctypes" [value]="acctype.value">
    {{ acctype.viewValue }}
    </mat-option>
</mat-select>
</code>```

In ts file you need to accept it as a parameter:

```<code>onSelect(element: Element){
    console.log(element)
}
</code>```

Body:
I have a table that I made with Angular Material. It contains some data made as an object in the ts file. See the code below:

import {Component} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html',
  styleUrls: ['./accounts.component.sass']
})

export class AccountsComponent {
  displayedColumns = ['Account Number', 'Account Name', 'Acctype1', 'Acctype2', 'Acctype3'];
  dataSource = new ExampleDataSource()

  acctypes = [
  {value: 'Tax', viewValue: 'Tax'},
  {value: 'Liabilities', viewValue: 'Liabilities'},
  {value: 'Enable', viewValue: 'Enable'},
  {value: 'Income Statement', viewValue: 'Income Statement'}
 ];

 onSelect(){
   console.log(DataSource)
 }
}

export interface Element {
  AccountNumber: string;
  AccountName: string;
  Acctype1: string;
  Acctype2: string;
  Acctype3: string;
}

const data: Element[] = [
  {AccountNumber: '001' , AccountName: 'Pepsi', Acctype1: 'H', Acctype2: 'D', Acctype3: 'P'},
  { AccountNumber: '002', AccountName: 'Coke', Acctype1: 'He', Acctype2: 'G', Acctype3: 'Wm'},
  { AccountNumber: '003', AccountName: 'Fanta', Acctype1: 'Li', Acctype2: 'Dk', Acctype3: 'R'},
  { AccountNumber: '004', AccountName: 'Faxe Kondi', Acctype1: 'Be', Acctype2: 'B', Acctype3: 'K'},
  { AccountNumber: '005', AccountName: 'Dr Pepper', Acctype1: 'B', Acctype2: 'Pn', Acctype3: 'M'},
  { AccountNumber: '006', AccountName: 'Mars', Acctype1: 'C', Acctype2: 'Mw', Acctype3: 'Xnm'},
  { AccountNumber: '007', AccountName: 'Snickers', Acctype1: 'N', Acctype2: 'D', Acctype3: 'P'},
  { AccountNumber: '008', AccountName: 'Converse', Acctype1: 'O', Acctype2: 'Z', Acctype3: 'Wc'},
  { AccountNumber: '009', AccountName: 'Adidas', Acctype1: 'F', Acctype2: 'Q', Acctype3: 'O'},
  { AccountNumber: '010', AccountName: 'Nike', Acctype1: 'Ne', Acctype2: 'Z', Acctype3: 'B'},

];

export class ExampleDataSource extends DataSource<any> {

  connect(): Observable<Element[]> {
    return Observable.of(data);
  }
  disconnect() {}
}

What I want to do is console.log all the data from the table and dropdown menu. Currently, when I select an option, the console logs

ƒ DataSource() {
    }

which obviously isn't what I need.

What am I doing wrong? This is the relevant HTML for the table:

  <form id='accForm'>
  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="Account Number">
      <mat-header-cell *matHeaderCellDef> Account Number </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.AccountNumber}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Account Name">
      <mat-header-cell *matHeaderCellDef> Account Name </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.AccountName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype1">
      <mat-header-cell *matHeaderCellDef> 2016/17 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element" id="accType">
          <mat-form-field>
            <mat-select name= 'acctype_id' [(ngModel)]="element.accType1" (change)="onSelect()" placeholder="Select Type">
              <mat-option *ngFor="let acctype of acctypes" [value]="acctype.value">
                {{ acctype.viewValue }}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype2">
      <mat-header-cell *matHeaderCellDef> 2015/16 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.Acctype2}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Acctype3">
      <mat-header-cell *matHeaderCellDef> 2014/15 Account Type </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.Acctype3}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
  </form>

I've been stuck on this for days, any help would be appreciated

Body:
You need to pass element as an argument in the onSelect method:

<mat-select name= 'acctype_id' [(ngModel)]="element.accType1" (change)="onSelect(element)" placeholder="Select Type">
    <mat-option *ngFor="let acctype of acctypes" [value]="acctype.value">
    {{ acctype.viewValue }}
    </mat-option>
</mat-select>

In ts file you need to accept it as a parameter:

onSelect(element: Element){
    console.log(element)
}


问:
LINQ to remove rows from datatable whose values in list<string>
I have datatable with two columns: id, title.
And i need to remove from the table the rows whose 'title' column values are included in the list.
Think the most correct way to do this is with linq to datatable, but dont know how.
Help me please build linq query.
Or can there be another effective way? More than 100k rows in this table.</p>

答:
You can use:</p>

```<code>List<DataRow> rowsToRemove = table.AsEnumerable()
    .Where(r => list.Contains(r.Field<string>("title")))
    .ToList();

rowsToRemove.ForEach(table.Rows.Remove);
</code>```

Body:
You can use:

List<DataRow> rowsToRemove = table.AsEnumerable()
    .Where(r => list.Contains(r.Field<string>("title")))
    .ToList();

rowsToRemove.ForEach(table.Rows.Remove);


问:
Unity Registration by convention - MatchingInterface property not found
I would like to use the registration by convention feature from unity in a project. Therefore, I followed this guide from Microsoft. Unfortunately, I am not able to find the property MatchingInterface from the class WithMappings. I would like to use this property since I have multiple classes and interface like IFoo and Foo.

Does someone solved this problem or have a idea?

My unity container version is 5.2.1., freshly installed from NuGet.

答: It seems that implementation of the method RegisterTypes() changed. The second parameter requires a function delegate which returns the types which are matching the some condition. In my case container.RegisterTypes(AllClasses.FromAssembliesInBasePath(), (c) => WithMappings.FromMatchingInterface(c)); solved the problem.


问:
How can reference the last item in a list in a Django template? {{ list.-1.key }}
if I have a variable in the context of unknown length, for example;

list=[{'key':'A'},{'key':'B'},{'key':'C'}]

How can I get the last object? {{ list.0.key }} works for the first, but {{ list.-1.key }} gives;

Could not parse the remainder: '-1.key' from 'list.-1.key'

答:
Thanks everyone for you help, it lead me to the realisation that I can use the with tag.</p>

```<code>{% with list|last as last %}
    {{ last.key }}
{% endwith %}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Thanks everyone for you help, it lead me to the realisation that I can use the with tag.

{% with list|last as last %}
    {{ last.key }}
{% endwith %}


问:
Rx scan(), cannot generate observable from seed and another observable
I have a seed value Triangle (Bool) and an observable that emits values Circle (Int). My intention is to generate a new observable (Triangle, Circle)  each time a value is emitted from that observable, transforming the Triangle value negating the current value. This is my marble diagram:

But I cannot achieve it, and I don't know if scan is the correct operator. This is my code:

```<code>typealias Triangle = Bool
typealias Circle = Int

func scan() {
    let triangle: Triangle = false
    circleObservable
        .scan(triangle, accumulator: ({ (triangle, circle) -> (Triangle, Circle) in
            return (!triangle, circle)
        }))
}
</code>```

This generates a compiler error:

Cannot convert value of type '(Triangle, Circle) -> (Triangle,
  Circle)' (aka '(Bool, Int) -> (Bool, Int)') to expected argument type
  '(_, _) -> _'

Thanks!

答: Perhaps 'throws' is missing? Have a look at this working example - https://github.com/maxvol/RaspSwift/blob/master/RaspSwift/RaspAggregator.swift</p>

Body:
I have a seed value Triangle (Bool) and an observable that emits values Circle (Int). My intention is to generate a new observable (Triangle, Circle)  each time a value is emitted from that observable, transforming the Triangle value negating the current value. This is my marble diagram:

But I cannot achieve it, and I don't know if scan is the correct operator. This is my code:

typealias Triangle = Bool
typealias Circle = Int

func scan() {
    let triangle: Triangle = false
    circleObservable
        .scan(triangle, accumulator: ({ (triangle, circle) -> (Triangle, Circle) in
            return (!triangle, circle)
        }))
}

This generates a compiler error:

Cannot convert value of type '(Triangle, Circle) -> (Triangle,
  Circle)' (aka '(Bool, Int) -> (Bool, Int)') to expected argument type
  '(_, _) -> _'

Thanks!


问:
How do I find the right syntax for my mysql version ?
I want to create a database for a simple authentication system but I just keep getting errors regarding the syntax and I can't find the appropriate one.

I connect to MySQL using : mysql -u root -p
with the password being : R2pay(XF%jVh(I got it at some point don't remember how)

Then I type CREATE DATABASE Filelist; and I get this error :

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

So I am like okay, I just have to change my password, but things get worse.

When I type this SET PASSWORD = PASSWORD ('123456'); I get :

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

I try to use a different method with ALTER USER 'root'@'localhost' IDENTIFIED BY 'elma3alem' PASSWORD EXPIRE; and I get :

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ALTER USER 'root'@'localhost' IDENTIFIED BY 'elma3alem' PASSWORD EXPIRE' at line 3

Even when I try to fix the "policy" problem with uninstall plugin validate_password; for example I get another error :

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

I am really getting desperate, everytime I try to find a solution I end up with even more errors, can't even count how much time I spent trying to fix mysql problems...

BTW this is what mysql --version displays :

mysql  Ver 14.14 Distrib 5.7.20, for Linux (x86_64) using  EditLine wrapper

Thanks beforehand.

答:
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

Means you paswword is too simple did you tryed another one like 'Draga123456'?


问:
open form2 from form1 and hide form 1 and then close form 1 when I close form 2
Okay so I have 2 forms Form1 and Form2.
Question: So I want to open Form2 when I click a button in Form1 and hide Form1 and after then I want to close Form1 when I close Form 2.</p>

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        Form2 f2 = new Form2(textBox1.Text);
        f2.Show();
        this.Hide();

    }
}

    public Form2(string s)
    {
        InitializeComponent();
        label1.Text = s;
    }
</code>```

答:
```<code>Form2 frm = new Form2();
frm.FormClosed += new FormClosedEventHandler(delegate(object s, FormClosedEventArgs e1) { this.Close(); });
this.Hide();
frm.Show();
</code>```

Body:
Okay so I have 2 forms Form1 and Form2.
Question: So I want to open Form2 when I click a button in Form1 and hide Form1 and after then I want to close Form1 when I close Form 2.

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        Form2 f2 = new Form2(textBox1.Text);
        f2.Show();
        this.Hide();

    }
}

    public Form2(string s)
    {
        InitializeComponent();
        label1.Text = s;
    }


问:
What does it mean that something is transitive in programming?
What does it mean that something is transitive with regard to programming? An example is the following (from here):

Using-directives are transitive for the purposes of unqualified
  lookup:

I am aware of the elaboration of this particular statement, however, I am striving for a more general programming related explanation.

答:
Transitive is a term from formal logic.   It means that "if A has a transitive relationship to B and B has the same relationship to C then A has that relationship to C".

For example, equality is a transitive relationship.   if A == B and B == C then transitivity is what allows A == C to be true.   Similarly, less-than is a transitive relationship, which means that if A < B and B < C then A < C.

For using directives, the meaning is that if a scope contains a using-directive that nominates a namespace name, which itself contains using-directive for a second namespace name, the effect is as if the using directives from the second namespace appear within the first.

In code, it means that

```<code>  namespace B
  {
        int foo;
  }

  namespace A
  {
       using namespace B;
  }

  using namespace A;

  int main()
  {
      foo = 42;       // resolves to B::foo
  }
</code>```

In the above, foo in main() resolves to A::foo.  Since A has a using namespace B,  foo in main() also resolves to B::foo.   Transitivity is the formal name for what makes that all work.

Body:
Transitive is a term from formal logic.   It means that "if A has a transitive relationship to B and B has the same relationship to C then A has that relationship to C".

For example, equality is a transitive relationship.   if A == B and B == C then transitivity is what allows A == C to be true.   Similarly, less-than is a transitive relationship, which means that if A < B and B < C then A < C.

For using directives, the meaning is that if a scope contains a using-directive that nominates a namespace name, which itself contains using-directive for a second namespace name, the effect is as if the using directives from the second namespace appear within the first.

In code, it means that

  namespace B
  {
        int foo;
  }

  namespace A
  {
       using namespace B;
  }

  using namespace A;

  int main()
  {
      foo = 42;       // resolves to B::foo
  }

In the above, foo in main() resolves to A::foo.  Since A has a using namespace B,  foo in main() also resolves to B::foo.   Transitivity is the formal name for what makes that all work.


问:
Gradient overlay on element on the right side
I have created a container with elements that is scrollable. I want the element on the right side to have a gradient overlay. How can I create that with CSS?

.container {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}

.element {
  min-width: 200px;
  height: 100px;
  background-color: red;
  margin-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
</div></code>```

https://codepen.io/naomilea/pen/RjZGaM

答:
Add this to the div element you want to add the gradient style</p>

```<code>.element {
  background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left, red , white); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(left, red, white); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(left, red, white); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to right, red , white); /* Standard syntax */
}
</code>```

Body:
I have created a container with elements that is scrollable. I want the element on the right side to have a gradient overlay. How can I create that with CSS?

.container {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: scroll;
  width: 1000px;
}

.element {
  min-width: 200px;
  height: 100px;
  background-color: red;
  margin-right: 10px;
}

https://codepen.io/naomilea/pen/RjZGaM

Body:
Add this to the div element you want to add the gradient style

.element {
  background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left, red , white); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(left, red, white); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(left, red, white); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to right, red , white); /* Standard syntax */
}


问:
android - download file with retrofit 2.0
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?

this is my interface:

```<code>public interface ApiService {

    @GET("uploads/{file_name}")
    Call<ServerResponse> downloadFile(@Path("file_name") String fileName);
}
</code>```

and this is my downloading code :

```<code>private void downloadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.downloadFile(file.getName());
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

            }
        });
    }
</code>```

答:
Probably, you are referring that the method "enqueue()" is called, but it's not the onResponse one.

Please wait some time (a minute is fine) and make sure that onResponse nor onFailure are called.

If you want more info, you can use the HTTP logging interceptor

Body:
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?

this is my interface:

public interface ApiService {

    @GET("uploads/{file_name}")
    Call<ServerResponse> downloadFile(@Path("file_name") String fileName);
}

and this is my downloading code :

private void downloadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.downloadFile(file.getName());
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

            }
        });
    }


问:
Uploading object to fireBase with image attached on android
Is there a way to upload object ,  Lets say for the example it is a User , with image to fireBase ?

According to what i have read i need to upload the user's image to storage and than upload the User to the Real time Db with the url i received when i uploaded the image in the first step .

is there a way on fire base to upload the user with the image on one Request so i will not have to

1 . do 2 request

2 . connect the request with an id so the user will know the image

3 . handle 2 requests responses .

Thanks .

答: You want to add "object" of user or the String containing the users info?</p>


问:
Taking Screenshot using Selenium 3.6 - Java - Webdriver
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
</code>```

Unfortunately the "copyFile" gives the following error:

```<code>The method copyFile(File, File) is undefined for the type FileUtils
</code>```

I have also imported all the required packages.

Can anyone help me to take screenshot?

答:
The error says it all the "copyFile" is giving an error. It is saying "The method copyFile(File, File) is undefined for the type FileUtils". It may be possible FileUtils is having multiple definition within your imports. So the solution would be as follows :

Use only:

```<code>import org.apache.commons.io.FileUtils;
</code>```

OR

Change your code as :

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
org.apache.commons.io.FileUtils.copyFile(scrFile, new File("C:\\tmp\\screenshot.png"));
</code>```

Body:
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Unfortunately the "copyFile" gives the following error:

The method copyFile(File, File) is undefined for the type FileUtils

I have also imported all the required packages.

Can anyone help me to take screenshot?

Body:
The error says it all the "copyFile" is giving an error. It is saying "The method copyFile(File, File) is undefined for the type FileUtils". It may be possible FileUtils is having multiple definition within your imports. So the solution would be as follows :

Use only:

import org.apache.commons.io.FileUtils;

OR

Change your code as :

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
org.apache.commons.io.FileUtils.copyFile(scrFile, new File("C:\\tmp\\screenshot.png"));


问:
Scatterplot with geom_text - showing subsample of labels
I am running the following R Code with ggplot2

```<code>library(ggplot2)

ggplot(result, aes(x=X2015, y=CPI.2015, color=Region)) +
    geom_point(size=6, alpha=0.6)  +
    geom_text(aes(label=Country), size=3,color = "black")
   #scale_x_discrete(breaks=seq(0,1000, 200))
</code>```

However, I get the following problems:

result plot

The x axis is completely unreadable. I have that line in my code (commented out) as above, but I get this "discrete value to continous scale" error.

I do not want to show ALL names, just some of them, to make it readable. Is that actually possible?

答:
Without original data it's hard to adjust parameters, but please try this:

Convert X2015 to numeric:

```<code>result$X2015 <- as.numeric(result$X2015)
</code>```

Randomly sample labels for geom_text:

```<code># Number of labels to show
nOfLabels <- 10
result$Country2 <- ifelse(1:nrow(result) %in% sample(1:nrow(result), nOfLabels),
                          result$Country, "")
</code>```

Here I randomly sample 10 countries and for rest return empty string "".

And plot your result using:

```<code>library(ggplot2)
ggplot(result, aes(X2015, CPI.2015, color = Region)) +
    geom_point(size = 6, alpha = 0.6)  +
    geom_text(aes(label = Country2), size = 3,color = "black") +
    scale_x_discrete(breaks = seq(0, 1000, 200))
</code>```

Body:
I am running the following R Code with ggplot2

library(ggplot2)

ggplot(result, aes(x=X2015, y=CPI.2015, color=Region)) +
    geom_point(size=6, alpha=0.6)  +
    geom_text(aes(label=Country), size=3,color = "black")
   #scale_x_discrete(breaks=seq(0,1000, 200))

However, I get the following problems:

result plot

The x axis is completely unreadable. I have that line in my code (commented out) as above, but I get this "discrete value to continous scale" error.

I do not want to show ALL names, just some of them, to make it readable. Is that actually possible?

Body:
Without original data it's hard to adjust parameters, but please try this:

Convert X2015 to numeric:

result$X2015 <- as.numeric(result$X2015)

Randomly sample labels for geom_text:

# Number of labels to show
nOfLabels <- 10
result$Country2 <- ifelse(1:nrow(result) %in% sample(1:nrow(result), nOfLabels),
                          result$Country, "")

Here I randomly sample 10 countries and for rest return empty string "".

And plot your result using:

library(ggplot2)
ggplot(result, aes(X2015, CPI.2015, color = Region)) +
    geom_point(size = 6, alpha = 0.6)  +
    geom_text(aes(label = Country2), size = 3,color = "black") +
    scale_x_discrete(breaks = seq(0, 1000, 200))


问:
Mule 3.7.3 and Jackson 2.9.0 issues-NoSuchMethodError
I am having lots of issues getting Mule to work with Jackson classes. The classes present in my final library only have the following files. To eliminate the possibility of maven pulling in other jackson libraries, I create a mule project without using maven and simply pull in the bare minimum libraries. However, it is failing with NoSuchMethodError for CSVMapper().reader(MyClass) etc. and later with

```<code>Caused by: java.lang.NoSuchMethodError:
               com.fasterxml.jackson.databind.JsonMappingException.<init>
         (Ljava/io/Closeable;Ljava/lang/String;)V
</code>```

jackson-core-2.9.0.jar
  jackson-databind-2.9.0.jar
  jackson-annotations-2.9.0.jar
  jackson-dataformat-csv-2.9.0.jar

I get NoSuchMethodError  when I call methods that are definitely in the classpath. To make matters worse the program runs fine outside of Mule.

It turns out that the following module mule-core.3.7.3 has an older version of Jackson i.e. 2.4.3. Unfortunately what works with version 2.9.0 now fails with

```<code> Too many entries: expected at most 1 (value #1 (18 chars) "20170822211046.581")
</code>```

How can solve this problem?

答: I  solved it by using the Jackson libraries provided by Mule i.e. version 2.4.3 for converted JSON to Java objects. For the CSV conversion to Map I used apache commons-csv replacing Jackson's CSVMapper.</p>

Body:
I am having lots of issues getting Mule to work with Jackson classes. The classes present in my final library only have the following files. To eliminate the possibility of maven pulling in other jackson libraries, I create a mule project without using maven and simply pull in the bare minimum libraries. However, it is failing with NoSuchMethodError for CSVMapper().reader(MyClass) etc. and later with

Caused by: java.lang.NoSuchMethodError:
               com.fasterxml.jackson.databind.JsonMappingException.<init>
         (Ljava/io/Closeable;Ljava/lang/String;)V

jackson-core-2.9.0.jar
  jackson-databind-2.9.0.jar
  jackson-annotations-2.9.0.jar
  jackson-dataformat-csv-2.9.0.jar

I get NoSuchMethodError  when I call methods that are definitely in the classpath. To make matters worse the program runs fine outside of Mule.

It turns out that the following module mule-core.3.7.3 has an older version of Jackson i.e. 2.4.3. Unfortunately what works with version 2.9.0 now fails with

 Too many entries: expected at most 1 (value #1 (18 chars) "20170822211046.581")

How can solve this problem?


问:
OS X Framework Library not loaded: 'Image not found'
I am trying to create a basic OS X Framework, right now I just have a test framework created: TestMacFramework.framework and I'm trying to import it into a brand new OS X Application project.

I have built the .framework file and imported it into the new project, The framework appears to link okay, and I can reference the public header file I added to the framework build phases section.

However, when I try to run the container Application I get the following Error:

```<code>dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
  Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
  Reason: image not found
</code>```

After a bit of googling I realised I needed to add a Copy Files section to my container application build phases, so I have done this and set it up like so...

However, I am still getting the runtime error. I'm obviously doing something wrong here, but the Apple developer library resource for this references Xcode 2, so isn't very helpful!

What have I missed?

UPDATE:

I can see in the build log that my TestMacFramework.framework is being copied into the .app contents/frameworks directory, but it isn't being installed to the Library/Frameworks directory on the HD

UPDATE 2:

The build links correctly if I manually copy the TestMacFramework.framework into the Library/Frameworks directory

答:
I had the same issue for a different reason.
I've created a new configuration to Debug and Release (under PROJECT -> Info tab -> Configuration).
And I had to change my pod frameworks shell script (Pods-"appName"-frameworks.sh , under Targets Support Files) to make it work.

[Xcode 9]

Body:
I am trying to create a basic OS X Framework, right now I just have a test framework created: TestMacFramework.framework and I'm trying to import it into a brand new OS X Application project.

I have built the .framework file and imported it into the new project, The framework appears to link okay, and I can reference the public header file I added to the framework build phases section.

However, when I try to run the container Application I get the following Error:

dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
  Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
  Reason: image not found

After a bit of googling I realised I needed to add a Copy Files section to my container application build phases, so I have done this and set it up like so...

However, I am still getting the runtime error. I'm obviously doing something wrong here, but the Apple developer library resource for this references Xcode 2, so isn't very helpful!

What have I missed?

UPDATE:

I can see in the build log that my TestMacFramework.framework is being copied into the .app contents/frameworks directory, but it isn't being installed to the Library/Frameworks directory on the HD

UPDATE 2:

The build links correctly if I manually copy the TestMacFramework.framework into the Library/Frameworks directory


问:
js async/await throws error on using this keyword
So, here's the code

```<code>let x = await this.storeFileName(fileName);
</code>```

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

```<code>   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }
</code>```

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

```<code>A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)
</code>```

答:
Ok, it seems a little bit tricky explaining what you need to do to make your functions async compatible.

So here I've updated your functions to show what I would do.

Notice the util.promisify, this is now baked into a latest version of Node.

```<code>async encodeName(x){
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x,'utf8', 'hex');
  encrypted += cipher.final('hex');
  if(encrypted.length>240){
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`;
  }
  return encrypted;
}

async storeFileName(x){
  let doc = { encName: x };
  filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
  pinsert = util.promisify(filesDb.insert);
  const newdoc = await pinsert(doc);
  return newdoc._id;
}
</code>```

Body:
So, here's the code

let x = await this.storeFileName(fileName);

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)

Body:
Ok, it seems a little bit tricky explaining what you need to do to make your functions async compatible.

So here I've updated your functions to show what I would do.

Notice the util.promisify, this is now baked into a latest version of Node.

async encodeName(x){
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x,'utf8', 'hex');
  encrypted += cipher.final('hex');
  if(encrypted.length>240){
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`;
  }
  return encrypted;
}

async storeFileName(x){
  let doc = { encName: x };
  filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
  pinsert = util.promisify(filesDb.insert);
  const newdoc = await pinsert(doc);
  return newdoc._id;
}