问:
Using Caliburn.Micro binding feature on an "inner" user control
I'm quite new to Caliburn.Micro, so I guess this has a simple answer (or at least I hope it has :))

I have a ViewModel with a property called ConnectedSystem that has a sub-property called Name.

In my View, I have the following XAML (excerpt):

```<code><StackPanel Orientation="Horizontal">
  <Label Content="Name:" />
  <TextBlock x:Name="ConnectedSystem_Name" />
</StackPanel>
</code>```

This works just fine, and the name is shown in the TextBlock as expected. However, ConnectedSystem has around 10 properties that should be displayed, and I don't want to copy-paste the XAML above 10 times inside my view. Instead I want to extract that XAML as a UserControl where I can set the LabelText and Text as properties.

I tried this, but I'm not sure how I can get Caliburn.Micro to pass the ConnectedSystem_Name into my UserControl automatically.

It might be a better way than using a UserControl here also, so the question is basically: What is the best way of putting this shared XAML as it's own control, and still be able to use Caliburn.Micros binding.

答:
What you need to do is use a ContentControl in your main view to display the ConnectedSystem property of the main view model. By using a ContentControl you will get included in the view model binding process and the view model binder rules will be applied. So you want your property (using the default implementation of Caliburn) to be of type ConnectedSystemViewModel and have a view named ConnectedSystemView. Then in the view used to display the parent you want a ContentControl with an x:Name of ConnectedSystem (the name of the ConnectedSystemViewModel property. This will cause the view model binder to connect the two and do its usual work. Here is some code for clarity:

ConnectedSystemView.xaml (the user control that conventions will use when specifying ContentControl as the control to display the connected system property of main view model)

```<code><UserControl x:Class="Sample.Views.ConnectedSystemView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Label Grid.Column="0"
                   Grid.Row="0">PropertyOne Label:</Label>
        <TextBox x:Name="PropertyOne"
                 Grid.Column="1"
                 Grid.Row="0"></TextBox>

        <TextBlock Grid.Column="0"
                   Grid.Row="1">PropertyTwo Label:</TextBlock>
        <TextBox x:Name="PropertyTwo"
                 Grid.Column="1"
                 Grid.Row="1"></TextBox>

        <!-- repeat the TextBlock, TextBox pair for the remaining
             properties three through ten -->
    </Grid>
</UserControl>
</code>```

ConnectedSystemViewModel.cs (the type of the ConnectedSystem property on your main view model)

```<code>namespace Sample.ViewModels
{
    public class ConnectedSystemViewModel : PropertyChangedBase
    {
        private string _propertyOne;
        public string PropertyOne
        {
            get { return _propertyOne; }
            set
            {
                _propertyOne = value;
                NotifyOfPropertyChange(() => PropertyOne);
            }
        }

        // these all need to be as above with NotifyPropertyChange,
        // omitted for brevity.
        public string PropertyTwo { get; set;}
        public string PropertyThree { get; set;}
        public string PropertyFour { get; set;}
        public string PropertyFive { get; set;}
        public string PropertySix { get; set;}
        public string PropertySeven { get; set;}
        public string PropertyEight { get; set;}
        public string PropertyNine { get; set;}
        public string PropertyTen { get; set;}
    }
}
</code>```

And in your main view define a ContentControl named relative to the main view model property of type ConnectedSystemViewModel

```<code><ContentControl x:Name="ConnectedSystem"></ContentControl>
</code>```

If I understand you question correctly this should be all you need to hook into the default Caliburn.Micro conventions. Obviously you will add the 10 ConnectedSystem properties to ConnectedSystemViewModel and appropriate controls with appropriate names to ConnectedSystemView to complete the implementation.

This way inside your main view you only need to define the one ContentControl to display the ConnectedSytem property (instead of 10 identical custom user controls) and conventions will determine the type of user control to use to fill the ContentControl.

Inside the ConnectedSystemView which will be inserted to the content property of your main views ContentControl via conventions, you have the controls you want to display your 10 connected system properties.

Body:
I'm quite new to Caliburn.Micro, so I guess this has a simple answer (or at least I hope it has :))

I have a ViewModel with a property called ConnectedSystem that has a sub-property called Name.

In my View, I have the following XAML (excerpt):

<StackPanel Orientation="Horizontal">

  <TextBlock x:Name="ConnectedSystem_Name" />
</StackPanel>

This works just fine, and the name is shown in the TextBlock as expected. However, ConnectedSystem has around 10 properties that should be displayed, and I don't want to copy-paste the XAML above 10 times inside my view. Instead I want to extract that XAML as a UserControl where I can set the LabelText and Text as properties.

I tried this, but I'm not sure how I can get Caliburn.Micro to pass the ConnectedSystem_Name into my UserControl automatically.

It might be a better way than using a UserControl here also, so the question is basically: What is the best way of putting this shared XAML as it's own control, and still be able to use Caliburn.Micros binding.

Body:
What you need to do is use a ContentControl in your main view to display the ConnectedSystem property of the main view model. By using a ContentControl you will get included in the view model binding process and the view model binder rules will be applied. So you want your property (using the default implementation of Caliburn) to be of type ConnectedSystemViewModel and have a view named ConnectedSystemView. Then in the view used to display the parent you want a ContentControl with an x:Name of ConnectedSystem (the name of the ConnectedSystemViewModel property. This will cause the view model binder to connect the two and do its usual work. Here is some code for clarity:

ConnectedSystemView.xaml (the user control that conventions will use when specifying ContentControl as the control to display the connected system property of main view model)

<UserControl x:Class="Sample.Views.ConnectedSystemView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Label Grid.Column="0"
                   Grid.Row="0">PropertyOne Label:</Label>
        <TextBox x:Name="PropertyOne"
                 Grid.Column="1"
                 Grid.Row="0"></TextBox>

        <TextBlock Grid.Column="0"
                   Grid.Row="1">PropertyTwo Label:</TextBlock>
        <TextBox x:Name="PropertyTwo"
                 Grid.Column="1"
                 Grid.Row="1"></TextBox>

        <!-- repeat the TextBlock, TextBox pair for the remaining
             properties three through ten -->
    </Grid>
</UserControl>

ConnectedSystemViewModel.cs (the type of the ConnectedSystem property on your main view model)

namespace Sample.ViewModels
{
    public class ConnectedSystemViewModel : PropertyChangedBase
    {
        private string _propertyOne;
        public string PropertyOne
        {
            get { return _propertyOne; }
            set
            {
                _propertyOne = value;
                NotifyOfPropertyChange(() => PropertyOne);
            }
        }

        // these all need to be as above with NotifyPropertyChange,
        // omitted for brevity.
        public string PropertyTwo { get; set;}
        public string PropertyThree { get; set;}
        public string PropertyFour { get; set;}
        public string PropertyFive { get; set;}
        public string PropertySix { get; set;}
        public string PropertySeven { get; set;}
        public string PropertyEight { get; set;}
        public string PropertyNine { get; set;}
        public string PropertyTen { get; set;}
    }
}

And in your main view define a ContentControl named relative to the main view model property of type ConnectedSystemViewModel

<ContentControl x:Name="ConnectedSystem"></ContentControl>

If I understand you question correctly this should be all you need to hook into the default Caliburn.Micro conventions. Obviously you will add the 10 ConnectedSystem properties to ConnectedSystemViewModel and appropriate controls with appropriate names to ConnectedSystemView to complete the implementation.

This way inside your main view you only need to define the one ContentControl to display the ConnectedSytem property (instead of 10 identical custom user controls) and conventions will determine the type of user control to use to fill the ContentControl.

Inside the ConnectedSystemView which will be inserted to the content property of your main views ContentControl via conventions, you have the controls you want to display your 10 connected system properties.


来源: stackexchange

问:
Accept inputs from the user until 5 unique inputs
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

```<code>while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)
</code>```

答:
You have three main issues here:

Using the set() constructor on an interable will create a set from its elements. In this case, the string returned from input. So for example:

```<code>>>> set("hello")
{'h', 'o', 'e', 'l'}
>>> set("54")
{'5', '4'}
</code>```

Not sure this is what you want. If you want to consider the input as a whole, you will have to use the add method of sets.

Secondly, you are re-initiazling your set on each input (as described above). Again, not sure this is what you actually want. You will have to initialize the set once, outside the loop.

You are checking if the "set" is actually the integer 5. What you probably meant, was to use len to check if len(mySet) == 5

All together a sample code could be:

my_set = set()
while len(my_set) != 5:
    my_set.add(input("Enter a number:"))
    print(my_set)
```

If you expect the input to be numbers, and want to store them as such, you can change to: mySet.add(int(input("Enter a number:"))) but keep in mind that this now might raise an exception so some error handling might be in place.

ContentLicense: CC BY-SA 4.0

Body:
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)

Body:
You have three main issues here:

Using the set() constructor on an interable will create a set from its elements. In this case, the string returned from input. So for example:

>>> set("hello")
{'h', 'o', 'e', 'l'}
>>> set("54")
{'5', '4'}

Not sure this is what you want. If you want to consider the input as a whole, you will have to use the add method of sets.

Secondly, you are re-initiazling your set on each input (as described above). Again, not sure this is what you actually want. You will have to initialize the set once, outside the loop.

You are checking if the "set" is actually the integer 5. What you probably meant, was to use len to check if len(mySet) == 5

All together a sample code could be:

my_set = set()
while len(my_set) != 5:
    my_set.add(input("Enter a number:"))
    print(my_set)

If you expect the input to be numbers, and want to store them as such, you can change to: mySet.add(int(input("Enter a number:"))) but keep in mind that this now might raise an exception so some error handling might be in place.


问:
How do remove the "Ok" button in popup (PySimpleGUI)
Typical popup:

sg.Popup("This is a simple popup")
```

This will show an "Ok" button with my text which I don't want.
How can I remove this button?

答:
You should be calling popup_no_buttons rather than changing the button_type parameter.  The documentation states that it's not meant to be used by users.

import PySimpleGUI as sg

sg.popup_no_buttons('This is a popup without buttons')
```

If you do use it, it's recommended you use the "enum" values for that parameter so that if the numbering changes your code will continue to function.  That value is sg.POPUP_BUTTONS_NO_BUTTONS

Body:
Typical popup:

sg.Popup("This is a simple popup")

This will show an "Ok" button with my text which I don't want.
How can I remove this button?

Body:
You should be calling popup_no_buttons rather than changing the button_type parameter.  The documentation states that it's not meant to be used by users.

import PySimpleGUI as sg

sg.popup_no_buttons('This is a popup without buttons')

If you do use it, it's recommended you use the "enum" values for that parameter so that if the numbering changes your code will continue to function.  That value is sg.POPUP_BUTTONS_NO_BUTTONS


问:
get mail as a file in outlook angular plugin to send it to server
I am working on a Angular plugin for outlook, we have a functionality to create a opinion based on the mail. for this we need to add the mail itself as a attachment to the form(A form for opinion creation) while creating the opinion and posting to our server.</p>

答: You can use EWS (makeEwsRequestAsync API) with the GetItem operation, or use REST API to obtain the item from the server. This will give you all the properties of the item. You can send this information to your backend and use it as needed. If that doesn't satisfy your needs, then please add a feature request to our UserVoice page. Feature requests on our UserVoice page are considered, when we go through our planning process.</p>


问:
How to get image size if I know its URL? Android (java)
I use Jsoup to read the website. But in html not all images have size information. So, if it is not there, I want to find out the image size in some other way, using the image source URL.</p>

答:
I would suggest use glide

```<code>dependencies {
  implementation 'com.github.bumptech.glide:glide:4.11.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
</code>```

and then load your image url using glide

```<code>        Glide.with(this)
        .asBitmap()
        .load(path)
        .into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                int width = bitmap.getWidth();
                int height = bitmap.getHeight()
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });
</code>```

Body:
I would suggest use glide

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.11.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}

and then load your image url using glide

        Glide.with(this)
        .asBitmap()
        .load(path)
        .into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                int width = bitmap.getWidth();
                int height = bitmap.getHeight()
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });


问:
T-SQL, why do we write GO
Why are there two GO's here in this code? When the query only has to run once why do we need to include it?</p>

```<code>USE AdventureWorks2016;
GO

SELECT
    Ord.SalesOrderID, Ord.OrderDate,
    (SELECT MAX(OrdDet.UnitPrice)
     FROM Sales.SalesOrderDetail AS OrdDet
     WHERE Ord.SalesOrderID = OrdDet.SalesOrderID) AS MaxUnitPrice
FROM Sales.SalesOrderHeader AS Ord;
GO
</code>```

答:
If it helps, GO isolates each batch

For example

```<code>Declare @v int = 25
Select @V;

go

Select @v ;
</code>```

The 1st SELECT executes fine and returns 25 while the 2nd throws an error

Title: T-SQL, why do we write GO

Body:
Why are there two GO's here in this code? When the query only has to run once why do we need to include it?

USE AdventureWorks2016;
GO

SELECT
    Ord.SalesOrderID, Ord.OrderDate,
    (SELECT MAX(OrdDet.UnitPrice)
     FROM Sales.SalesOrderDetail AS OrdDet
     WHERE Ord.SalesOrderID = OrdDet.SalesOrderID) AS MaxUnitPrice
FROM Sales.SalesOrderHeader AS Ord;
GO

Body:
If it helps, GO isolates each batch

For example

Declare @v int = 25
Select @V;

go

Select @v ;

The 1st SELECT executes fine and returns 25 while the 2nd throws an error


问:
Unable to extract page tittle and page_source using IEDriverServer and Selenium through Python
i have just started selenium coding.
i have python 3.6.6, executing following code on jupyter notebook (with chrome broser)

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Ie("C:\\Python 36\\IEDriverServer.exe")
driver.get('https://google.com')

print(driver.title)
print(driver.page_source)
driver.close()
</code>```

this is giving following output:

WebDriver
WebDriverThis is the initial start page for the WebDriver server.

In this process an IE browser gets open and goes to google.com (any desired site) but not getting closed

答:
To extract the Page Titile and the Page Source you need to:

Invoke the FQDN i.e https://www.google.com/ through get(), i.e. including www.

Induce WebDriverWait for a clickable WebElement to be interactive.

While ending your program invoke quit() instead of close().

You can use the following solution:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Ie("C:\\Python 36\\IEDriverServer.exe")
driver.get('https://www.google.com/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q")))
print(driver.title)
print(driver.page_source)
driver.quit()
</code>```

Body:
i have just started selenium coding.
i have python 3.6.6, executing following code on jupyter notebook (with chrome broser)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Ie("C:\\Python 36\\IEDriverServer.exe")
driver.get('https://google.com')

print(driver.title)
print(driver.page_source)
driver.close()

this is giving following output:

WebDriver
WebDriverThis is the initial start page for the WebDriver server.

In this process an IE browser gets open and goes to google.com (any desired site) but not getting closed

Body:
To extract the Page Titile and the Page Source you need to:

Invoke the FQDN i.e https://www.google.com/ through get(), i.e. including www.

Induce WebDriverWait for a clickable WebElement to be interactive.

While ending your program invoke quit() instead of close().

You can use the following solution:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Ie("C:\\Python 36\\IEDriverServer.exe")
driver.get('https://www.google.com/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q")))
print(driver.title)
print(driver.page_source)
driver.quit()


问:
Can't convert time strings from csv to datetime
I have a csv file with 2 timestamps per row consisting of date, time and a value:

```<code>02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456
</code>```

When I try to convert date and time string to datetime:

```<code>with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)
</code>```

I got:

```<code>Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'
</code>```

Why is that? When I try something like

```<code>date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')
</code>```

it works fine.

EDIT:
I swapped format and time string and used some other data:

```<code>02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994
</code>```

Error is still:

```<code>Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'
</code>```

Seems to be the 00:25:03. But %I is the 24hour format.

答: You give the parameters in the wrong order. The date string needs to go first, then the format string.</p>

Body:
I have a csv file with 2 timestamps per row consisting of date, time and a value:

02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456

When I try to convert date and time string to datetime:

with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)

I got:

Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'

Why is that? When I try something like

date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')

it works fine.

EDIT:
I swapped format and time string and used some other data:

02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994

Error is still:

Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'

Seems to be the 00:25:03. But %I is the 24hour format.


问:
iOS 13.2 MKTileOverlay occasionally won't render
I'm having an issue where in iOS 13.2 (probably also from iOS 13), loading offline map tile using MKTileOverlay occasionally won't be able to render, leaving the tile blank, there seems to be no issue with MKTileOverlay's subclass at all as it worked well in iOS 12 and below. I have 2 MKTileOverlay class (1 add grid and 1 load map tile file, default MKTileOverlay), both won't be able to load on that blank tile with default MKTileOverlayRenderer, other overlays seems to appear fine.

The issue seems to be resolved itself if I go to home screen and go back to the app, causing the tiles to reload. Is this a bug from iOS MapKit itself? Does anyone have temporary solution for this? Thank you.

Code for adding overlay:

```<code>let overlay = MKTileOverlay(urlTemplate: urlTemplate)
overlay.canReplaceMapContent = true
overlay.maximumZ = 19
mapView.insertOverlay(overlay, at: 0, level: .aboveLabels)
</code>```

Renderer:

```<code>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKTileOverlay {
        let renderer = MKTileOverlayRenderer(tileOverlay: overlay as! MKTileOverlay)
        return renderer
    }

    return MKOverlayRenderer()
}
</code>```

答:
As I noted in a comment to the original question I was having the same problem, but it is now largely resolved, so I thought I'd post what worked for me.

The problem for me occurred in the following method

```<code>- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData * __nullable tileData, NSError * __nullable error))result{
</code>```

where the custom tile would fail to load even when it was being presented with what appeared to be valid NSData.

I found that the problem was reduced if I used jpegs instead of pngs for my custom tiles, but it was only when I changed the way that I was handling the tile data did the problem largely go away. (I largely, because I still get the occasional unloaded tile, but I'd say it's 100x less often than I was getting them before).

The following method is my Xamarin.iOS implementation of it, but you should be able to see the principle for Swift or Objective C.

The key is the difference in the way the NSData is created. Instead of calling the UrlForTilePath method, I create a UIImage from the tile path and then use the UIImageJPEGRepresentation (AsJPEG in C#) to create the NSData.

```<code>   public override void LoadTileAtPath(MKTileOverlayPath path, MKTileOverlayLoadTileCompletionHandler result)
    {
        //I was using this prior to ios 13.2

        //NSUrl url = this.URLForTilePath(path);
        //NSData tileData = NSData.FromFile(url.AbsoluteString);
        //result(tileData, null);

        //Now I use this

        String folderPath = "tiles/" + path.Z + "/" + path.X + "/";
        String tilePath = NSBundle.MainBundle.PathForResource(path.Y.ToString(), "jpg", folderPath);
        String blankPath = NSBundle.MainBundle.PathForResource("tile", "jpg");

        try
        {
            //does the file exist?
            UIImage tile;
            if (File.Exists(tilePath))
            {
                tile = UIImage.FromFile(tilePath);
                if (tile == null)
                {
                    Console.WriteLine("Error Loading " + path.Z + " " + path.Y + " " + path.X);
                    //This may be redundant, as I'm not getting any errors here, even when the tile doesn't display
                }
            }
            else
            {
                tile = UIImage.FromFile(blankPath);
            }

            NSData tileData = tile.AsJPEG();
            result(tileData, null);
        }
        catch (Exception ex)
        {

        }
    }
</code>```

Body:
I'm having an issue where in iOS 13.2 (probably also from iOS 13), loading offline map tile using MKTileOverlay occasionally won't be able to render, leaving the tile blank, there seems to be no issue with MKTileOverlay's subclass at all as it worked well in iOS 12 and below. I have 2 MKTileOverlay class (1 add grid and 1 load map tile file, default MKTileOverlay), both won't be able to load on that blank tile with default MKTileOverlayRenderer, other overlays seems to appear fine.

The issue seems to be resolved itself if I go to home screen and go back to the app, causing the tiles to reload. Is this a bug from iOS MapKit itself? Does anyone have temporary solution for this? Thank you.

Code for adding overlay:

let overlay = MKTileOverlay(urlTemplate: urlTemplate)
overlay.canReplaceMapContent = true
overlay.maximumZ = 19
mapView.insertOverlay(overlay, at: 0, level: .aboveLabels)

Renderer:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKTileOverlay {
        let renderer = MKTileOverlayRenderer(tileOverlay: overlay as! MKTileOverlay)
        return renderer
    }

    return MKOverlayRenderer()
}

Body:
As I noted in a comment to the original question I was having the same problem, but it is now largely resolved, so I thought I'd post what worked for me.

The problem for me occurred in the following method

- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData * __nullable tileData, NSError * __nullable error))result{

where the custom tile would fail to load even when it was being presented with what appeared to be valid NSData.

I found that the problem was reduced if I used jpegs instead of pngs for my custom tiles, but it was only when I changed the way that I was handling the tile data did the problem largely go away. (I largely, because I still get the occasional unloaded tile, but I'd say it's 100x less often than I was getting them before).

The following method is my Xamarin.iOS implementation of it, but you should be able to see the principle for Swift or Objective C.

The key is the difference in the way the NSData is created. Instead of calling the UrlForTilePath method, I create a UIImage from the tile path and then use the UIImageJPEGRepresentation (AsJPEG in C#) to create the NSData.

   public override void LoadTileAtPath(MKTileOverlayPath path, MKTileOverlayLoadTileCompletionHandler result)
    {
        //I was using this prior to ios 13.2

        //NSUrl url = this.URLForTilePath(path);
        //NSData tileData = NSData.FromFile(url.AbsoluteString);
        //result(tileData, null);

        //Now I use this

        String folderPath = "tiles/" + path.Z + "/" + path.X + "/";
        String tilePath = NSBundle.MainBundle.PathForResource(path.Y.ToString(), "jpg", folderPath);
        String blankPath = NSBundle.MainBundle.PathForResource("tile", "jpg");

        try
        {
            //does the file exist?
            UIImage tile;
            if (File.Exists(tilePath))
            {
                tile = UIImage.FromFile(tilePath);
                if (tile == null)
                {
                    Console.WriteLine("Error Loading " + path.Z + " " + path.Y + " " + path.X);
                    //This may be redundant, as I'm not getting any errors here, even when the tile doesn't display
                }
            }
            else
            {
                tile = UIImage.FromFile(blankPath);
            }

            NSData tileData = tile.AsJPEG();
            result(tileData, null);
        }
        catch (Exception ex)
        {

        }
    }


问:
How can I manipulate the child node of this element?
My Chrome Extension needs to change the size of the child node to the following.

Notice how the 'width' is set for the parent DIV...my Chrome Extension did that.

I can show the following element in the console by:

```<code>var divContainer2 = $(divContainer)[0];
console.log('Now divContainer is: ', divContainer2);
</code>```

The element shown in the console by the above (just the start of it, but showing the parent/child relationship):

```<code><div class="v7wOcf ZGnOx" style="margin-top: 80px; width: 1207px;">
        <div jscontroller="Zptowf" jsaction="R6jwd:hKrBwc;c96EGd:v8OFqc;QmtCl:.CLIENT;qVp5ue:.CLIENT;AE9bOd:.CLIENT;MmB7ud:.CLIENT;zkkUY:.CLIENT;lyIVcf:.CLIENT;wuANJc:.CLIENT;voP7ud:.CLIENT" jsmodel="PuTOgd IaLzN tZ2gdc dSSknb PTCFbe ephE9e lkzLle OqPTdc nQnzVc VeaFK uArcre" data-without-stream-item-materials="" class="DReKqd" data-submission-id="1" data-view-id="46"><div jscontroller="cs6ocd" jsaction="rcuQ6b:npT2md;KDsQaf:Qp7hp;qFgNIJf-Wvd9Cc Yiql6e iTy5c editable" tabindex="0" role="textbox" aria-required="true" aria-multiline="true"
</code>```

I want to apply similar styling to the child (the DIV on the second line...with the 'jscontroller').

To make things very explicit I've tried:

```<code>var divContainer3 = divContainer2[0];
var divContainer3 = divContainer2.children[0];
</code>```

And others...

What am I missing? Why can't I grab the childnode of the object I can so clearly push to console and manipulate?

Thank you for any help/direction/guidance...

答:
The issue wasn't syntax...it was dynamic content loading...and so when I was grabbing the childNodes (or trying to) the element didn't exist.

What continues to be confusing for me is that the CONSOLE will show an element called out in console.log even though it didn't exist at the time the particular line of code ran.

So I could SEE the element, and it's nodes/length, in the console but the very next line of code that simply logged the length would come up zero. Because when the length code ran the element didn't really exist.

I added a little 'wait' routine to make sure the thing is there before I try to manipulate it.

Body:
My Chrome Extension needs to change the size of the child node to the following.

Notice how the 'width' is set for the parent DIV...my Chrome Extension did that.

I can show the following element in the console by:

var divContainer2 = $(divContainer)[0];
console.log('Now divContainer is: ', divContainer2);

The element shown in the console by the above (just the start of it, but showing the parent/child relationship):

<div jscontroller="cs6ocd" jsaction="rcuQ6b:npT2md;KDsQaf:Qp7hp;qFgNIJf-Wvd9Cc Yiql6e iTy5c editable" tabindex="0" role="textbox" aria-required="true" aria-multiline="true"

I want to apply similar styling to the child (the DIV on the second line...with the 'jscontroller').

To make things very explicit I've tried:

var divContainer3 = divContainer2[0];
var divContainer3 = divContainer2.children[0];

And others...

What am I missing? Why can't I grab the childnode of the object I can so clearly push to console and manipulate?

Thank you for any help/direction/guidance...


问:
How to make this "Reverse number function work", python 3?
Reverse a inputted number...

Please help me turn this input number into a defined function that spits out a
that number in reverse order?  I am trying to make it exist inside a function(N1) with a request for input being inside "def". While the leg work is being done inside the "while" loop and being iterated through until all there is no remainder, and all that is left is the input number to be printed in reverse.

```<code>def n1(n):
    rev = 0

    n = int(input("Enter number: "))

    while(n>0):

        dig=n%10

        rev=rev*10+dig

        n=n//10

        return print("reverse of the number: ", rev)

n2 = n1

print(n2(n))
</code>```

答:
Your indentation is wrong. You should not return inside the while loop.

```<code>def reverse_number(number):
    reversed = 0
    while number > 0:
        number, digit = divmod(number, 10)
        reversed = reversed * 10 + digit
    return reversed

n = int(input("Enter number: "))
print(reverse_number(n))
</code>```

Body:
Reverse a inputted number...

Please help me turn this input number into a defined function that spits out a
that number in reverse order?  I am trying to make it exist inside a function(N1) with a request for input being inside "def". While the leg work is being done inside the "while" loop and being iterated through until all there is no remainder, and all that is left is the input number to be printed in reverse.

def n1(n):
    rev = 0

    n = int(input("Enter number: "))

    while(n>0):

        dig=n%10

        rev=rev*10+dig

        n=n//10

        return print("reverse of the number: ", rev)

n2 = n1

print(n2(n))

Body:
Your indentation is wrong. You should not return inside the while loop.

def reverse_number(number):
    reversed = 0
    while number > 0:
        number, digit = divmod(number, 10)
        reversed = reversed * 10 + digit
    return reversed

n = int(input("Enter number: "))
print(reverse_number(n))


问:
Redirection after Sign In Authentication
I have a login screen where I have implemented authentication via a GraphQL API. The authentication works fine and I get a token but I can't figure out how to continue. Once the Sign In button is hit, I want to redirect to the /panel page. If the authentication doesn't work, the user should not access /panel.</p>

<p>/panel works fine in general when I am using React Router. But I want to access it right after clicking the sign in button. How can I fix this? </p>

```<code>export default class LoginPage extends Component <{}, { email: string,password: string }>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
  }

  _SignIn = (e: { preventDefault: () => void; }) => {
    axios({
      url: 'https://xzy/graphql',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        query: `
            mutation{
               loginMethod(email: "${this.state.email}",
               password: "${this.state.password}")
}`,
      },
    })
      .then((result: { data: any }) => {
        const token = JSON.stringify(result.data.data.loginEmail).slice(1,-1);
        if (token){
          alert(token)
          //return <Redirect to='/users' />
        }
      })
      .catch((err: any) => {
        console.log(err);
      });
      e.preventDefault();
  };

  render() {
    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div style={{
         display: 'flex',
         flexDirection: 'column',
         alignItems: 'center'}}>
          <Avatar>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form style={{width: '100%'}} noValidate>
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              onChange={e => {
                this.setState({email: e.target.value})
              }}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              onChange={e => {
                this.setState({password: e.target.value})
            }}
            />
            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            />
            <Button
            onClick={this._SignIn}
            >
            Submit</Button>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2">
                  Forgot password?
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
        <Box mt={8}>
          <Copyright />
        </Box>
      </Container>
    );
  }
}
</code>```

答:
Well you can push "/users" to history and for so,
first import

```<code>const createHistory = require("history").createBrowserHistory;
</code>```

then add

```<code>  let history = createHistory();
history.push("/");
</code>```

Make sure that your  in index.js is wrapped
with history

```<code><Router history={history}>
      <div>
          <HashRouter>
        <App />
        </HashRouter>
      </div>
    </Router>
</code>```

Edit 2

```<code>  function App() {
  const checkAuth = () => {
    const token = localStorage.getItem('token');
    if (!token) {
      return false;
    }

    try {
      // { exp: 12903819203 }
      const { exp } = decode(token);

      if (exp < new Date().getTime() / 1000) {
        return false;
      }

    } catch (e) {
      return false;
    }

    return true;
  }

  const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (
        <Component {...props} />
      ) : (
          <Redirect to={{ pathname: '/login' }} />
        )
    )} />
  )

  return (
    <div className="row">
      <Router>
        <Switch>
          <AuthRoute exact path="/users" component={Users} />
          <AuthRoute exact path="/panels" component={Panels} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/logout" component={Logout} />
        </Switch>
      </Router>
    </div>
  );
}
</code>```

Body:
I have a login screen where I have implemented authentication via a GraphQL API. The authentication works fine and I get a token but I can't figure out how to continue. Once the Sign In button is hit, I want to redirect to the /panel page. If the authentication doesn't work, the user should not access /panel.

/panel works fine in general when I am using React Router. But I want to access it right after clicking the sign in button. How can I fix this?

export default class LoginPage extends Component <{}, { email: string,password: string }>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
  }

  _SignIn = (e: { preventDefault: () => void; }) => {
    axios({
      url: 'https://xzy/graphql',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        query: `
            mutation{
               loginMethod(email: "${this.state.email}",
               password: "${this.state.password}")
}`,
      },
    })
      .then((result: { data: any }) => {
        const token = JSON.stringify(result.data.data.loginEmail).slice(1,-1);
        if (token){
          alert(token)
          //return <Redirect to='/users' />
        }
      })
      .catch((err: any) => {
        console.log(err);
      });
      e.preventDefault();
  };

  render() {
    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />

          <Avatar>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form style={{width: '100%'}} noValidate>
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              onChange={e => {
                this.setState({email: e.target.value})
              }}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              onChange={e => {
                this.setState({password: e.target.value})
            }}
            />
            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            />
            <Button
            onClick={this._SignIn}
            >
            Submit</Button>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2">
                  Forgot password?
                </Link>
              </Grid>
            </Grid>
          </form>

        <Box mt={8}>
          <Copyright />
        </Box>
      </Container>
    );
  }
}

Body:
Well you can push "/users" to history and for so,
first import

const createHistory = require("history").createBrowserHistory;

then add

  let history = createHistory();
history.push("/");

Make sure that your  in index.js is wrapped
with history

<Router history={history}>
      <div>
          <HashRouter>
        <App />
        </HashRouter>
      </div>
    </Router>

Edit 2

  function App() {
  const checkAuth = () => {
    const token = localStorage.getItem('token');
    if (!token) {
      return false;
    }

    try {
      // { exp: 12903819203 }
      const { exp } = decode(token);

      if (exp < new Date().getTime() / 1000) {
        return false;
      }

    } catch (e) {
      return false;
    }

    return true;
  }

  const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (
        <Component {...props} />
      ) : (
          <Redirect to={{ pathname: '/login' }} />
        )
    )} />
  )

  return (
    <div className="row">
      <Router>
        <Switch>
          <AuthRoute exact path="/users" component={Users} />
          <AuthRoute exact path="/panels" component={Panels} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/logout" component={Logout} />
        </Switch>
      </Router>
    </div>
  );
}


问:
In MySQL SERVER 8.0 the PASSWORD function not working
Error while executing the PASSWORD function in MySQL Server version 8.0.12

I have the following query:

```<code>SELECT *
FROM users
WHERE login = 'FABIO'
  AND pwd = PASSWORD('2018')
LIMIT 0, 50000
</code>```

I am getting this error:

Error Code: 1064. 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

Body:
Error while executing the PASSWORD function in MySQL Server version 8.0.12

I have the following query:

SELECT *
FROM users
WHERE login = 'FABIO'
  AND pwd = PASSWORD('2018')
LIMIT 0, 50000

I am getting this error:

Error Code: 1064. 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

Body:
If you need a replacement hash to match the password() function, use this: SHA1(UNHEX(SHA1()));

E.g.

mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass')                        |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+

and replacement that gives the same answer in version 8:

mysql> SELECT CONCAT('*', UPPER(SHA1(UNHEX(SHA1('mypass')))));
+-------------------------------------------------+
| CONCAT('*', UPPER(SHA1(UNHEX(SHA1('mypass'))))) |
+-------------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4       |
+-------------------------------------------------+


问:
bash script to rename files based on a calculation
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

```<code>#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

答:
REWRITE due to misunderstanding of the formula and the updated var names. Still no subprocesses apart from mv and ls.

```<code>#!/bin/bash

tiles=`ls -d */*/*`

for thisPath in $tiles
do
   thisFile=${thisPath#*/*/}
   oldY=${thisFile%.png}
   zoomX=${thisPath%/*}
   zoom=${thisPath%/*/*}
   newY=$(((1<<zoom) - oldY - 1))
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done

Body:
REWRITE due to misunderstanding of the formula and the updated var names. Still no subprocesses apart from mv and ls.

#!/bin/bash

tiles=`ls -d */*/*`

for thisPath in $tiles
do
   thisFile=${thisPath#*/*/}
   oldY=${thisFile%.png}
   zoomX=${thisPath%/*}
   zoom=${thisPath%/*/*}
   newY=$(((1<<zoom) - oldY - 1))
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done


问:
In Brian Gladman's AES implementation, how is aes_encrypt_key128 being mapped to aes_xi?
I'm able to follow the code path up to a certain point.  Briefly:

The program accepts an ASCII hexadecimal string and converts it to binary.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L366-L382

If arg[3] is an “E”, it defines an aes_encrypt_ctx struct and passes the key, the calculated key_len value, and the aes_encrypt_ctx stuct to aes_encrypt_key.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L409-L412

aes_encrypt_key is defined in aeskey.c.  Depending on key_len, the function aes_encrypt_key<NNN> is called.  They key and the struct are passed to the function.  https://github.com/BrianGladman/aes/blob/master/aeskey.c#L545-L547

But where is the aes_encrypt_key128 function?

This line appears to be my huckleberry:

```<code>#  define aes_xi(x) aes_ ## x
</code>```

So hopefully I'm onto something.  It's mapping aes_encrypt_key128 to aes_xi(encrypt_key128), right?

```<code>AES_RETURN aes_xi(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1])
{   uint32_t    ss[4];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#ifdef ENC_KS_UNROLL
    ke4(cx->ks, 0);  ke4(cx->ks, 1);
    ke4(cx->ks, 2);  ke4(cx->ks, 3);
    ke4(cx->ks, 4);  ke4(cx->ks, 5);
    ke4(cx->ks, 6);  ke4(cx->ks, 7);
    ke4(cx->ks, 8);
#else
    {   uint32_t i;
        for(i = 0; i < 9; ++i)
            ke4(cx->ks, i);
    }
#endif
    ke4(cx->ks, 9);
    cx->inf.l = 0;
    cx->inf.b[0] = 10 * AES_BLOCK_SIZE;

#ifdef USE_VIA_ACE_IF_PRESENT
    if(VIA_ACE_AVAILABLE)
        cx->inf.b[1] = 0xff;
#endif
    MARK_AS_ENCRYPTION_CTX(cx);
    return EXIT_SUCCESS;
}
</code>```

I see some pattern replacement happening here.  I guess at this point I was wondering if you could point me to the docs that explain this feature of #define?

答:
I've been at this a while but it started to become clear to me that there is pattern matching going on in the pre-processing macros of the aeskey.c file.  The only doc I've been able to find is this one.

Pattern Matching

The ## operator is used to concatenate two tokens into one token. This
  is provides a very powerful way to do pattern matching. Say we want to
  write a IIF macro, we could write it like this:

```<code>#define IIF(cond) IIF_ ## cond
#define IIF_0(t, f) f
#define IIF_1(t, f) t
</code>```

However there is one problem with this approach. A subtle side effect
  of the ## operator is that it inhibits expansion. Heres an example:

```<code>#define A() 1
//This correctly expands to true
IIF(1)(true, false)
// This will however expand to
IIF_A()(true, false)
// This is because A() doesn't expand to 1,
// because its inhibited by the ## operator
IIF(A())(true, false)
</code>```

The way to work around this is to use another indirection. Since this
  is commonly done we can write a macro called CAT that will concatenate
  without inhibition.

```<code>#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__
</code>```

So now we can write the IIF macro (its called IIF right now, later we
  will show how to define a more generalized way of defining an IF
  macro):

```<code>#define IIF(c) PRIMITIVE_CAT(IIF_, c)
#define IIF_0(t, ...) __VA_ARGS__
#define IIF_1(t, ...) t

#define A() 1
//This correctly expands to true
IIF(1)(true, false)
// And this will also now correctly expand to true
IIF(A())(true, false)
</code>```

With pattern matching we can define other operations, such as COMPL
  which takes the complement:

```<code>#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)
#define COMPL_0 1
#define COMPL_1 0
</code>```

or BITAND:

```<code>#define BITAND(x) PRIMITIVE_CAT(BITAND_, x)
#define BITAND_0(y) 0
#define BITAND_1(y) y
</code>```

We can define increment and decrement operators as macros:

```<code>#define INC(x) PRIMITIVE_CAT(INC_, x)
#define INC_0 1
#define INC_1 2
#define INC_2 3
#define INC_3 4
#define INC_4 5
#define INC_5 6
#define INC_6 7
#define INC_7 8
#define INC_8 9
#define INC_9 9

#define DEC(x) PRIMITIVE_CAT(DEC_, x)
#define DEC_0 0
#define DEC_1 0
#define DEC_2 1
#define DEC_3 2
#define DEC_4 3
#define DEC_5 4
#define DEC_6 5
#define DEC_7 6
#define DEC_8 7
#define DEC_9 8
</code>```

Body:
I'm able to follow the code path up to a certain point.  Briefly:

The program accepts an ASCII hexadecimal string and converts it to binary.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L366-L382

If arg[3] is an “E”, it defines an aes_encrypt_ctx struct and passes the key, the calculated key_len value, and the aes_encrypt_ctx stuct to aes_encrypt_key.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L409-L412

aes_encrypt_key is defined in aeskey.c.  Depending on key_len, the function aes_encrypt_key<NNN> is called.  They key and the struct are passed to the function.  https://github.com/BrianGladman/aes/blob/master/aeskey.c#L545-L547

But where is the aes_encrypt_key128 function?

This line appears to be my huckleberry:

#  define aes_xi(x) aes_ ## x

So hopefully I'm onto something.  It's mapping aes_encrypt_key128 to aes_xi(encrypt_key128), right?

AES_RETURN aes_xi(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1])
{   uint32_t    ss[4];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#ifdef ENC_KS_UNROLL
    ke4(cx->ks, 0);  ke4(cx->ks, 1);
    ke4(cx->ks, 2);  ke4(cx->ks, 3);
    ke4(cx->ks, 4);  ke4(cx->ks, 5);
    ke4(cx->ks, 6);  ke4(cx->ks, 7);
    ke4(cx->ks, 8);
#else
    {   uint32_t i;
        for(i = 0; i < 9; ++i)
            ke4(cx->ks, i);
    }
#endif
    ke4(cx->ks, 9);
    cx->inf.l = 0;
    cx->inf.b[0] = 10 * AES_BLOCK_SIZE;

#ifdef USE_VIA_ACE_IF_PRESENT
    if(VIA_ACE_AVAILABLE)
        cx->inf.b[1] = 0xff;
#endif
    MARK_AS_ENCRYPTION_CTX(cx);
    return EXIT_SUCCESS;
}

I see some pattern replacement happening here.  I guess at this point I was wondering if you could point me to the docs that explain this feature of #define?

Body:
I've been at this a while but it started to become clear to me that there is pattern matching going on in the pre-processing macros of the aeskey.c file.  The only doc I've been able to find is this one.

Pattern Matching

The ## operator is used to concatenate two tokens into one token. This
  is provides a very powerful way to do pattern matching. Say we want to
  write a IIF macro, we could write it like this:

#define IIF(cond) IIF_ ## cond
#define IIF_0(t, f) f
#define IIF_1(t, f) t

However there is one problem with this approach. A subtle side effect
  of the ## operator is that it inhibits expansion. Heres an example:

#define A() 1
//This correctly expands to true
IIF(1)(true, false)
// This will however expand to
IIF_A()(true, false)
// This is because A() doesn't expand to 1,
// because its inhibited by the ## operator
IIF(A())(true, false)

The way to work around this is to use another indirection. Since this
  is commonly done we can write a macro called CAT that will concatenate
  without inhibition.

#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__

So now we can write the IIF macro (its called IIF right now, later we
  will show how to define a more generalized way of defining an IF
  macro):

#define IIF(c) PRIMITIVE_CAT(IIF_, c)
#define IIF_0(t, ...) __VA_ARGS__
#define IIF_1(t, ...) t

#define A() 1
//This correctly expands to true
IIF(1)(true, false)
// And this will also now correctly expand to true
IIF(A())(true, false)

With pattern matching we can define other operations, such as COMPL
  which takes the complement:

#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)
#define COMPL_0 1
#define COMPL_1 0

or BITAND:

#define BITAND(x) PRIMITIVE_CAT(BITAND_, x)
#define BITAND_0(y) 0
#define BITAND_1(y) y

We can define increment and decrement operators as macros:

#define INC(x) PRIMITIVE_CAT(INC_, x)
#define INC_0 1
#define INC_1 2
#define INC_2 3
#define INC_3 4
#define INC_4 5
#define INC_5 6
#define INC_6 7
#define INC_7 8
#define INC_8 9
#define INC_9 9

#define DEC(x) PRIMITIVE_CAT(DEC_, x)
#define DEC_0 0
#define DEC_1 0
#define DEC_2 1
#define DEC_3 2
#define DEC_4 3
#define DEC_5 4
#define DEC_6 5
#define DEC_7 6
#define DEC_8 7
#define DEC_9 8


问:
Does Ada have any idiomatic rules on when to use a function versus a procedure with an output parameter?
You can assign to a variable by having a function return a value to it:

My_Int : Integer := My_Math_Func [(optional params)];

Or you can do it like this with a procedure (assuming My_Int has already been declared):

My_Math_Proc ([optional params;] [in] out My_Int);

Obviously a procedure can't initialize a variable like the function does in the first example, but I'm hoping for some concrete, practical rules on when and why to pick one over the other.

答:
Two to get you started...

When more than one result is to be returned, a procedure with several OUT parameters is often a good choice.

When the size of the object is unknown prior to the subprogram call, an OUT parameter cannot be used because it would have to be declared precisely the right size, but a function return can set the size by initialising the variable in the caller. This is commonly used with a variable declared in a Declare block, which can hold a different sized string each time it is invoked.

This example shows the variable "text" initialised by calling a Read_File function, to hold the contents of a different file on each iteration of the loop. Safe, no "malloc" or "free" or pointers necessary. (Filename is an array of filenames in this example)

```<code>for i in 1 .. last_file loop
   declare
      text : String := Read_File(Filename(i));
      -- the size of "text" is determined by the file contents
   begin
      --   process the text here.
      for j in text'range loop
         if text(j) = '*' then
         ...
      end loop;
   end
end loop;
</code>```

Edit : And I suppose I'd better mention the underlying mathematical principle, since Ada is based more closely on mathematical logic than many other languages.

Functions and procedures are both subprograms, but for different purposes:

a function is an abstraction over an expression : like a mathematical operator (and an operator in Ada is just a function). Ideally, it provides a result from a number of operands and nothing else, leaving them unchanged and having no state and no side effects. This ideal is called a "pure function" (and applying "pragma pure" asks the compiler to check its purity) - similar restrictions apply in functional programming (FP) languages. Pure functions allow a whole bunch of optimisation (because reordering them doesn't change results). In practice Ada is not that strict, allowing impure functions too.

a procedure is an abstraction over a statement. It generally has some physical effect (such as changing state) since it doesn't deliver a result.

So the logical separation between expressions and statements is carried over into subprograms (abstractions) as the separation between functions and procedures.

And this is probably the best way to decide which to use.

Body:
Two to get you started...

When more than one result is to be returned, a procedure with several OUT parameters is often a good choice.

When the size of the object is unknown prior to the subprogram call, an OUT parameter cannot be used because it would have to be declared precisely the right size, but a function return can set the size by initialising the variable in the caller. This is commonly used with a variable declared in a Declare block, which can hold a different sized string each time it is invoked.

This example shows the variable "text" initialised by calling a Read_File function, to hold the contents of a different file on each iteration of the loop. Safe, no "malloc" or "free" or pointers necessary. (Filename is an array of filenames in this example)

for i in 1 .. last_file loop
   declare
      text : String := Read_File(Filename(i));
      -- the size of "text" is determined by the file contents
   begin
      --   process the text here.
      for j in text'range loop
         if text(j) = '*' then
         ...
      end loop;
   end
end loop;

Edit : And I suppose I'd better mention the underlying mathematical principle, since Ada is based more closely on mathematical logic than many other languages.

Functions and procedures are both subprograms, but for different purposes:

a function is an abstraction over an expression : like a mathematical operator (and an operator in Ada is just a function). Ideally, it provides a result from a number of operands and nothing else, leaving them unchanged and having no state and no side effects. This ideal is called a "pure function" (and applying "pragma pure" asks the compiler to check its purity) - similar restrictions apply in functional programming (FP) languages. Pure functions allow a whole bunch of optimisation (because reordering them doesn't change results). In practice Ada is not that strict, allowing impure functions too.

a procedure is an abstraction over a statement. It generally has some physical effect (such as changing state) since it doesn't deliver a result.

So the logical separation between expressions and statements is carried over into subprograms (abstractions) as the separation between functions and procedures.

And this is probably the best way to decide which to use.


问:
What to use instead of "testDevices" in AdMob for real ADs?
I am using firebase_admob package of Flutter for displaying ads and it works on non-real ads, they appear on app. Also I updated adUnitIds to integrate ads to my real admob account.

But, when I want to display real ads I don't have any idea how to do that.

```<code>MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['game', 'words'],
  testDevices: <String>[],
);

BannerAd myBanner = BannerAd(
  adUnitId: "[here is my unit ID]",
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  },
);

void initState() {
    FirebaseAdMob.instance.initialize(appId: "[my admob ID]");
    super.initState();
}
</code>```

So, what should I write on testDevices in order to show ads to real users without need to write every user's device id manually?

答:
I found the answer with some experiments. I placed my app on Play Store, it works fine, it displays ads.

Basically, if you want to show real ads rather than test ads let testDevices be null, do not fill it.

And do not forget to put your real unit id from AdMob account as

```<code>adUnitId: "your unit ID",
</code>```

Final code should look like this:

```<code>...
MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['game', 'words'],
);

BannerAd myBanner = BannerAd(
  adUnitId: "your unit ID",
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  },
);
...
</code>```

Body:
I am using firebase_admob package of Flutter for displaying ads and it works on non-real ads, they appear on app. Also I updated adUnitIds to integrate ads to my real admob account.

But, when I want to display real ads I don't have any idea how to do that.

MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['game', 'words'],
  testDevices: <String>[],
);

BannerAd myBanner = BannerAd(
  adUnitId: "[here is my unit ID]",
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  },
);

void initState() {
    FirebaseAdMob.instance.initialize(appId: "[my admob ID]");
    super.initState();
}

So, what should I write on testDevices in order to show ads to real users without need to write every user's device id manually?

Body:
I found the answer with some experiments. I placed my app on Play Store, it works fine, it displays ads.

Basically, if you want to show real ads rather than test ads let testDevices be null, do not fill it.

And do not forget to put your real unit id from AdMob account as

adUnitId: "your unit ID",

Final code should look like this:

...
MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['game', 'words'],
);

BannerAd myBanner = BannerAd(
  adUnitId: "your unit ID",
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  },
);
...


问:
quasiquote/quote in lua?
In Lisp, I can have:

```<code>(a b c d e f g)
</code>```

which means

```<code>look up b, c, d, e, f, g
look up a; apply value of a to above
</code>```

Then, I can also have:

```<code>`(a b c d e f g)
</code>```

which is the equiv to

```<code> (list 'a 'b 'c 'd 'e 'f 'g)
</code>```

Now, in lua, I can have:

```<code>[snipplet 1]
foo = {
  Foo,
  {Cat, cat},
  {Dog, dog}
};
</code>```

Which ends up most likely expanding into:
    { nil, { nil, nil}, {nil, nil}}

Whereas what I really want is something like:

```<code>[snipplet 2]
{ "Foo", {"Cat", "cat"}, {"Dog", "dog"}}
</code>```

Is there some backquote-like method in lua?

I find [snipplet 1] to be more visually pleasing than [snipplet 2], but what I mean is snipplet 2.

Thanks!

答: Consider a function that parses a string containing the Lisp syntax and constructs a table from that.</p>

ContentLicense: CC BY-SA 2.5

Title: quasiquote/quote in lua?

Body:
In Lisp, I can have:

(a b c d e f g)

which means

look up b, c, d, e, f, g
look up a; apply value of a to above

Then, I can also have:

`(a b c d e f g)

which is the equiv to

 (list 'a 'b 'c 'd 'e 'f 'g)

Now, in lua, I can have:

[snipplet 1]
foo = {
  Foo,
  {Cat, cat},
  {Dog, dog}
};

Which ends up most likely expanding into:
    { nil, { nil, nil}, {nil, nil}}

Whereas what I really want is something like:

[snipplet 2]
{ "Foo", {"Cat", "cat"}, {"Dog", "dog"}}

Is there some backquote-like method in lua?

I find [snipplet 1] to be more visually pleasing than [snipplet 2], but what I mean is snipplet 2.

Thanks!


问:
NameError: name 'HTMLSession' is not defined when calling yahoo_fin.options.get_expiration_dates()
I'm calling yahoo_fin.options.get_expiration_dates() from a very simple code, such that it's unlikely that I have loaded other modules with the same name.

My whole code is this:

```<code>import matplotlib.pyplot as plt
import pandas as pd

from numpy import *
from yahoo_fin import options

plt.style.use("seaborn")

expirationDates = options.get_expiration_dates("goog")
</code>```

The output of the last line is:

```<code>NameError: name 'HTMLSession' is not defined
</code>```

Can you help me understand what's going on?

答:
yahoo_fin requires requests-html for a few of its functions, including the yahoo_fin.options.get_expiration_dates method.  You can install it using pip (it requires Python 3.6+):

```<code>pip install requests-html
</code>```

Once installed, you need to restart your Python session.  This link provides information on what functionality requires requests-html.

Body:
I'm calling yahoo_fin.options.get_expiration_dates() from a very simple code, such that it's unlikely that I have loaded other modules with the same name.

My whole code is this:

import matplotlib.pyplot as plt
import pandas as pd

from numpy import *
from yahoo_fin import options

plt.style.use("seaborn")

expirationDates = options.get_expiration_dates("goog")

The output of the last line is:

NameError: name 'HTMLSession' is not defined

Can you help me understand what's going on?

Body:
yahoo_fin requires requests-html for a few of its functions, including the yahoo_fin.options.get_expiration_dates method.  You can install it using pip (it requires Python 3.6+):

pip install requests-html

Once installed, you need to restart your Python session.  This link provides information on what functionality requires requests-html.


问:
How to return data trough tables Laravel
Hello we have three entities, Instruments, Composers and Tracks.

Instruments and Composers are linked with a many to many relationship.

When you click on a instrument(id) i would like to display the number of composers that have write some "tracks" for that instrument.

I use this code, but i think it's not the cleanest why, and I didn't understood well Eloquent and his methods in laravel , can you help me?
p.s it works but I don't fill okay..

my Instruments controller:

```<code>public function getInstrument( Instrument $instrument){
$id_compositori= ComposerInstrument::where('instrument_id', $instrument->id)->pluck('composer_id')->toArray();
$compositori = Composer::whereIn('id',$id_compositori)->get();

return  view('instrumentcomposer',compact(['id_compositori','instrument','compositori']));
</code>```

}

my view:

```<code>@foreach($compositori as $composer)
<div class="col-lg-3 col-md-4 col-6">
  <img class="img-fluid img-thumbnail" src=" https://i.picsum.photos/id/619/200/300.jpg?grayscale" alt="">

<h2>Wrote by  {{ $composer->name }} </h2>

   </div>

@endforeach
</code>```

Thank you

edit
 Track model

```<code>class Track extends Model
{
   public function instrument()
   {
       return $this->belongsTo(Instrument::class,'instrument_id','id');
   }

   public function composer()
   {
       return $this->belongsTo(Composer::class,'composer_id','id');
   }
}
</code>```

Instrument model

```<code>class Instrument extends Model
{
   public function composers1()
   {
       return $this->belongstoMany(ComposerInstrument::class);
   }
   public function tracks()
   {
       return $this->hasMany(Track::class);
   }
   public function composers()
   {
       return $this->hasMany(Composer::class);
   }
</code>```

Composer model

```<code>class Composer extends Model
{

   public function instruments()
   {
       return $this->belongstoMany(ComposerInstrument::class);
   }

   public function tracks()
   {
       return $this->hasMany(Track::class);
   }
   public function instruments2()
   {
       return $this->hasMany(Instrument::class);
   }

   }

</code>```

Pivot Table Model

```<code>class ComposerInstrument extends Model
{
   protected $table = 'composer_instrument';
   protected $fillable = ['composer_id','instrument_id'];
   public function instruments()
   {
       return $this->hasMany(Instrument::class);
   }

   public function composers()
   {
       return $this->hasMany(Composer::class);
   }
}

</code>```

Sorry i'm very newbie

答:
The first parameter of belongsToMany() should reference the model that it has that relationship with not the pivot model.

Change the composers() method your in your Instrument model to be:

```<code>public function composers()
{
    return $this->belongsToMany(Composer::class);
}
</code>```

Then your controller code can be:

```<code>public function getInstrument(Instrument $instrument)
{
    return  view('instrumentcomposer', compact('instrument'));
}
</code>```

Lastly, your blade file would be:

```<code>@foreach($instrument->composers as $composer)
    <div class="col-lg-3 col-md-4 col-6">
        <img class="img-fluid img-thumbnail" src="https://i.picsum.photos/id/619/200/300.jpg?grayscale" alt="">

        <h2>Wrote by  {{ $composer->name }} </h2>
   </div>
@endforeach
</code>```

Body:
Hello we have three entities, Instruments, Composers and Tracks.

Instruments and Composers are linked with a many to many relationship.

When you click on a instrument(id) i would like to display the number of composers that have write some "tracks" for that instrument.

I use this code, but i think it's not the cleanest why, and I didn't understood well Eloquent and his methods in laravel , can you help me?
p.s it works but I don't fill okay..

my Instruments controller:

public function getInstrument( Instrument $instrument){
$id_compositori= ComposerInstrument::where('instrument_id', $instrument->id)->pluck('composer_id')->toArray();
$compositori = Composer::whereIn('id',$id_compositori)->get();

return  view('instrumentcomposer',compact(['id_compositori','instrument','compositori']));

}

my view:

@foreach($compositori as $composer)

Wrote by  {{ $composer->name }}

@endforeach

Thank you

edit
 Track model

class Track extends Model
{
   public function instrument()
   {
       return $this->belongsTo(Instrument::class,'instrument_id','id');
   }

   public function composer()
   {
       return $this->belongsTo(Composer::class,'composer_id','id');
   }
}

Instrument model

class Instrument extends Model
{
   public function composers1()
   {
       return $this->belongstoMany(ComposerInstrument::class);
   }
   public function tracks()
   {
       return $this->hasMany(Track::class);
   }
   public function composers()
   {
       return $this->hasMany(Composer::class);
   }

Composer model

class Composer extends Model
{

   public function instruments()
   {
       return $this->belongstoMany(ComposerInstrument::class);
   }

   public function tracks()
   {
       return $this->hasMany(Track::class);
   }
   public function instruments2()
   {
       return $this->hasMany(Instrument::class);
   }

   }

Pivot Table Model

class ComposerInstrument extends Model
{
   protected $table = 'composer_instrument';
   protected $fillable = ['composer_id','instrument_id'];
   public function instruments()
   {
       return $this->hasMany(Instrument::class);
   }

   public function composers()
   {
       return $this->hasMany(Composer::class);
   }
}

Sorry i'm very newbie

Body:
The first parameter of belongsToMany() should reference the model that it has that relationship with not the pivot model.

Change the composers() method your in your Instrument model to be:

public function composers()
{
    return $this->belongsToMany(Composer::class);
}

Then your controller code can be:

public function getInstrument(Instrument $instrument)
{
    return  view('instrumentcomposer', compact('instrument'));
}

Lastly, your blade file would be:

@foreach($instrument->composers as $composer)
    <div class="col-lg-3 col-md-4 col-6">
        <img class="img-fluid img-thumbnail" src="https://i.picsum.photos/id/619/200/300.jpg?grayscale" alt="">

        <h2>Wrote by  {{ $composer->name }} </h2>
   </div>
@endforeach


问:
Functional programming: How to model relationships?
I wonder how to model relationships in functional programming.

Let's take employees, for example:
Employees can have friendships with 0..n colleagues.
Friendships are always mutual: if A is a friend of B then B is a friend of A.

How can I model this? I had 3 ideas (listed below). Each of them has downsides.

First try:

```<code>type Employee =
  { name : string
    friendships : Employee list
  }

// My list is mutable because I want to be able to update employees.
// I suppose the same problems would occur with e. g. Elmish.
let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are copies. Changes to an employee would have to be propagated manually.
*)
</code>```

Second try:

```<code>type EmployeeId = int

type Employee =
  { id : EmployeeId
    name : string
    friendships : EmployeeId list
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are not modeled as mutual.
   When the friendship of an employee changes,
   the friend's friendships don't change accordingly.
*)
</code>```

Third try:

```<code>type EmployeeId = int

type Friendships = list<EmployeeId * EmployeeId>

type Employee =
  { id : EmployeeId
    name : string
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   After deleting an employee from the list,
   employeeFriendships contain invalid "references"
   to the deleted Employee.
*)
</code>```

Can this be done better? Thank you.

答:
The question is not about functional programming as it involves mutation. An Object-Oriented solution would work well because the important thing is encapsulating the logic in one place and hiding it behind a safe API. Fortunately your choice of F# is still good as F# is a very good OO language.

type Employee(id:int, name:string) =
    static let employees = ResizeArray<Employee>[]()
    static let friendships = ResizeArray<int*int>()
    static let getEmployee(eid:EmployeeId) = employees |> Seq.find(fun e -> e.Id = eid)
    member t.Id = id
    member t.Name = name
    member t.Friends =
        let friendIds = friendships ...
        friendIds |> Array.map getEmployee
    static member Employees = employees |> Array.ofSeq
    static member Add = employees.Add
    static member Remove(e:Employee) =
        employees.Remove e |> ignore
        friendships |> Seq.filter (fun (a,b) -> a = e.Id || b = e.Id)
        |> Seq.iter (friendships.Remove >> ignore)
    static member AddFriend(e1:Employee, e2:Employee) = ...

```

You could do the same with records and/or modules too by making things private.

Body:
I wonder how to model relationships in functional programming.

Let's take employees, for example:
Employees can have friendships with 0..n colleagues.
Friendships are always mutual: if A is a friend of B then B is a friend of A.

How can I model this? I had 3 ideas (listed below). Each of them has downsides.

First try:

type Employee =
  { name : string
    friendships : Employee list
  }

// My list is mutable because I want to be able to update employees.
// I suppose the same problems would occur with e. g. Elmish.
let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are copies. Changes to an employee would have to be propagated manually.
*)

Second try:

type EmployeeId = int

type Employee =
  { id : EmployeeId
    name : string
    friendships : EmployeeId list
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are not modeled as mutual.
   When the friendship of an employee changes,
   the friend's friendships don't change accordingly.
*)

Third try:

type EmployeeId = int

type Friendships = list<EmployeeId * EmployeeId>

type Employee =
  { id : EmployeeId
    name : string
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   After deleting an employee from the list,
   employeeFriendships contain invalid "references"
   to the deleted Employee.
*)

Can this be done better? Thank you.

Body:
The question is not about functional programming as it involves mutation. An Object-Oriented solution would work well because the important thing is encapsulating the logic in one place and hiding it behind a safe API. Fortunately your choice of F# is still good as F# is a very good OO language.

type Employee(id:int, name:string) =
    static let employees = ResizeArray<Employee>[]()
    static let friendships = ResizeArray<int*int>()
    static let getEmployee(eid:EmployeeId) = employees |> Seq.find(fun e -> e.Id = eid)
    member t.Id = id
    member t.Name = name
    member t.Friends =
        let friendIds = friendships ...
        friendIds |> Array.map getEmployee
    static member Employees = employees |> Array.ofSeq
    static member Add = employees.Add
    static member Remove(e:Employee) =
        employees.Remove e |> ignore
        friendships |> Seq.filter (fun (a,b) -> a = e.Id || b = e.Id)
        |> Seq.iter (friendships.Remove >> ignore)
    static member AddFriend(e1:Employee, e2:Employee) = ...

You could do the same with records and/or modules too by making things private.


问:
NetworkX node_shape from svg
Is it possible to use an svg image to create a custom node in Networkx? For example:

Using this svg image: https://upload.wikimedia.org/wikipedia/commons/6/67/Firefox_Logo%2C_2017.svg

And in peudocode:

```<code>nx.draw(G, pos=pos, node_shape=svg_string)
</code>```

And end up with something like this:

How could this be done?

答:
Convert the Graph to Dot 1.

Draw the node as an image. 2.

Title: NetworkX node_shape from svg

Body:
Is it possible to use an svg image to create a custom node in Networkx? For example:

Using this svg image: https://upload.wikimedia.org/wikipedia/commons/6/67/Firefox_Logo%2C_2017.svg

And in peudocode:

nx.draw(G, pos=pos, node_shape=svg_string)

And end up with something like this:

How could this be done?


问:
javascript autoclick does not seem to autoclick
I'm really new to javascript and jquery and I'm trying to get a button to autoclick from an existing code base. I am having trouble getting the button to do that even though this is what I've been following How to auto click an input button.

The code is below. I've tried using both .submit() and .click() but the start-game-btn doesn't seem to get pressed either way. I've put a console.log within the button whenever it's pressed and the message doesn't seem to get logged.

```<code>console.log("loading...")

$(() => {

  $("#start-game-btn").click(event => {
    console.log("start-game")
    $("#errors").text("")
    event.preventDefault()
    const height = parseInt($("#height").val())
    const width = parseInt($("#width").val())
    const food = parseInt($("#food").val())
    let MaxTurnsToNextFoodSpawn = 0
    if ($("#food-spawn-chance").val()) {
      MaxTurnsToNextFoodSpawn = parseInt($("#food-spawn-chance").val())
    }
    const snakes = []

    $(".snake-group").each(function() {
      const url = "http://0.0.0.0:8080/"//$(".snake-url", $(this)).val()
      console.log(url)
      if (!url) {
        return
      }
      snakes.push({
        name: "M1",//$(".snake-name", $(this)).val(),
        url
      })
    })
    if (snakes.length === 0) {
      $("#errors").text("No snakes available")
    }
    console.log(12)
    fetch("http://localhost:3005/games", {
      method: "POST",
      body: JSON.stringify({
        width,
        height,
        food,
        MaxTurnsToNextFoodSpawn,
        "snakes": snakes,
      })
    }).then(resp => resp.json())
      .then(json => {
        const id = json.ID
        fetch(`http://localhost:3005/games/${id}/start`, {
          method: "POST"
        }).then(_ => {
          $("#board").attr("src", `http://localhost:3009?engine=http://localhost:3005&game=${id}`)
        }).catch(err => $("#errors").text(err))
      })
      .catch(err => $("#errors").text(err))
  })
  console.log("ready!")
})

window.onload = function(){
    var button = document.getElementById('start-game-btn');
    button.form.submit();
    console.log("Done!!")
}

</code>```

Everytime I refresh the page the log shows:

```<code>loading...
ready!
Done!!
</code>```

What I think it should be logging is (or at least that's what I'm trying to achieve):

```<code>loading...
start-game
ready!
Done!!
</code>```

答:
submit() does not work because it is for submitting forms.

button.form.submit(); does not work because it assumes your button is part of a form.

As it looks like you are using jQuery, try just calling the jQuery click function without any parameters using a jQuery selector.

eg.

$("#start-game-btn").click();

Body:
I'm really new to javascript and jquery and I'm trying to get a button to autoclick from an existing code base. I am having trouble getting the button to do that even though this is what I've been following How to auto click an input button.

The code is below. I've tried using both .submit() and .click() but the start-game-btn doesn't seem to get pressed either way. I've put a console.log within the button whenever it's pressed and the message doesn't seem to get logged.

console.log("loading...")

$(() => {

  $("#start-game-btn").click(event => {
    console.log("start-game")
    $("#errors").text("")
    event.preventDefault()
    const height = parseInt($("#height").val())
    const width = parseInt($("#width").val())
    const food = parseInt($("#food").val())
    let MaxTurnsToNextFoodSpawn = 0
    if ($("#food-spawn-chance").val()) {
      MaxTurnsToNextFoodSpawn = parseInt($("#food-spawn-chance").val())
    }
    const snakes = []

    $(".snake-group").each(function() {
      const url = "http://0.0.0.0:8080/"//$(".snake-url", $(this)).val()
      console.log(url)
      if (!url) {
        return
      }
      snakes.push({
        name: "M1",//$(".snake-name", $(this)).val(),
        url
      })
    })
    if (snakes.length === 0) {
      $("#errors").text("No snakes available")
    }
    console.log(12)
    fetch("http://localhost:3005/games", {
      method: "POST",
      body: JSON.stringify({
        width,
        height,
        food,
        MaxTurnsToNextFoodSpawn,
        "snakes": snakes,
      })
    }).then(resp => resp.json())
      .then(json => {
        const id = json.ID
        fetch(`http://localhost:3005/games/${id}/start`, {
          method: "POST"
        }).then(_ => {
          $("#board").attr("src", `http://localhost:3009?engine=http://localhost:3005&game=${id}`)
        }).catch(err => $("#errors").text(err))
      })
      .catch(err => $("#errors").text(err))
  })
  console.log("ready!")
})

window.onload = function(){
    var button = document.getElementById('start-game-btn');
    button.form.submit();
    console.log("Done!!")
}

Everytime I refresh the page the log shows:

loading...
ready!
Done!!

What I think it should be logging is (or at least that's what I'm trying to achieve):

loading...
start-game
ready!
Done!!


问:
How can I execute a python script directly (without prefixing by the python command) from bash?
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

```<code>manage.py runserver
</code>```

However when I do this it says:

```<code>bash: manage.py: command not found
</code>```

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

答: manage.py needs to be executable. Try: chmod +x manage.py

Body:
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

manage.py runserver

However when I do this it says:

bash: manage.py: command not found

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.


问:
Recursive Common Table Expressions: why use UNION ALL?
Recursive CTEs include an anchor query and a recursive query. The anchor selects one or more rows to begin with, and the recursive selects the rest. The rows are combined with a UNION ALL clause.

If the two inner queries don’t return the same rows, why do you need to combine them with a UNION ALL clause, and not just UNION ? As far as I am aware, the purpose of UNION ALL is to include duplicate rows.

This appears to be a requirement with Microsoft SQL, but not with PostgreSQL.

Or is there more to the picture?

Thanks to @MartinSmith’s comment, this appears to be answered in Why does a Recursive CTE in Transact-SQL require a UNION ALL and not a UNION?

I’m voting to close this question.

答:
You say "just UNION".  In general, your thinking should be "just UNION ALL".

UNION incurs extra overhead for removing duplicate rows.  You only want to incur that overhead if you actually want to remove duplicates.  The default should always be UNION ALL, unless you want that extra operation.


问:
Cordova ble.write i can't send data (Android)

I have an Android App build in Apache Cordova, it works with Bluetooth 4.0(BLE) the plugin GitHub repostory indicates this shape for send information to a ble device (in my case a HM10 module):

this function writes data to a characteristic.

ble.write(device_id, service_uuid, characteristic_uuid, data, success, failure);
Description
Function write writes data to a characteristic.

Parameters:
device_id: UUID or MAC address of the peripheral
service_uuid: UUID of the BLE service
characteristic_uuid: UUID of the BLE characteristic
data: binary data, use an ArrayBuffer
success: Success callback function that is invoked when the connection is successful. [optional]
failure: Error callback function, invoked when error occurs. [optional]

I have tried to send data for this way but failure function is called immediately

```<code>    function startBed() {
        var UiidS="FFE0"; //UUID SERVICE: AT+UUID? => 0xFFE0
        var UiidC="FFE1"; //UUID CHARACTERISTICS AT+CHAR? => 0xFFE1

        var data = new Uint8Array(1);
        data[0] = 1;
        setTimeout(ble.write(hMac,UiidS,UiidC,data.buffer,success,failure),2000);
        function success() {
            document.getElementById("btstate1").innerHTML = "Dato enviado!!!";
            }
        function failure() {
            document.getElementById("btstate1").innerHTML = "Dato NO enviado!!!";
            var time=2000;
            navigator.vibrate(time);
        }
    }
</code>```

if I take the text box value and send it directly, the HM10 receives an unrecognized characters like Ó.

```<code>        var UiidS="FFE0";
        var UiidC="FFE1";
        var dato =document.getElementById("btstate6").value;
        setTimeout(ble.write(hMac,UiidS,UiidC,dato,success,failure),2000);
</code>```

In conclution
I don't know why the module not receive the data correctly or in other cases the data isn't send. Maybe is for something of UUID.

答:
Using a different plugin (https://github.com/randdusing/cordova-plugin-bluetoothle)
I used the following

```<code>var encodedString = bluetoothle.bytesToEncodedString([145,0,14,0,255]);
bluetoothle.write(this.writeSuccess.bind(this), this.writeError.bind(this), {
        "value": encodedString,
        "service": this.serviceUuid,
        "characteristic": this.serviceCharacteristic,
        "type": "noResponse",
        "address": this.currentConnectedDevice
    });
</code>```

Where

```<code>// From plugin source:
encodedStringToBytes: function(string) {
    var data = atob(string);
    var bytes = new Uint8Array(data.length);
    for (var i = 0; i < bytes.length; i++)
    {
        bytes[i] = data.charCodeAt(i);
    }
    return bytes;
},
bytesToEncodedString: function(bytes) {
    return btoa(String.fromCharCode.apply(null, bytes));
},
</code>```

I hope this helps

Body:
I have an Android App build in Apache Cordova, it works with Bluetooth 4.0(BLE) the plugin GitHub repostory indicates this shape for send information to a ble device (in my case a HM10 module):

this function writes data to a characteristic.

ble.write(device_id, service_uuid, characteristic_uuid, data, success, failure);
Description
Function write writes data to a characteristic.

Parameters:
device_id: UUID or MAC address of the peripheral
service_uuid: UUID of the BLE service
characteristic_uuid: UUID of the BLE characteristic
data: binary data, use an ArrayBuffer
success: Success callback function that is invoked when the connection is successful. [optional]
failure: Error callback function, invoked when error occurs. [optional]

I have tried to send data for this way but failure function is called immediately

    function startBed() {
        var UiidS="FFE0"; //UUID SERVICE: AT+UUID? => 0xFFE0
        var UiidC="FFE1"; //UUID CHARACTERISTICS AT+CHAR? => 0xFFE1

        var data = new Uint8Array(1);
        data[0] = 1;
        setTimeout(ble.write(hMac,UiidS,UiidC,data.buffer,success,failure),2000);
        function success() {
            document.getElementById("btstate1").innerHTML = "Dato enviado!!!";
            }
        function failure() {
            document.getElementById("btstate1").innerHTML = "Dato NO enviado!!!";
            var time=2000;
            navigator.vibrate(time);
        }
    }

if I take the text box value and send it directly, the HM10 receives an unrecognized characters like Ó.

        var UiidS="FFE0";
        var UiidC="FFE1";
        var dato =document.getElementById("btstate6").value;
        setTimeout(ble.write(hMac,UiidS,UiidC,dato,success,failure),2000);

In conclution
I don't know why the module not receive the data correctly or in other cases the data isn't send. Maybe is for something of UUID.

Body:
Using a different plugin (https://github.com/randdusing/cordova-plugin-bluetoothle)
I used the following

var encodedString = bluetoothle.bytesToEncodedString([145,0,14,0,255]);
bluetoothle.write(this.writeSuccess.bind(this), this.writeError.bind(this), {
        "value": encodedString,
        "service": this.serviceUuid,
        "characteristic": this.serviceCharacteristic,
        "type": "noResponse",
        "address": this.currentConnectedDevice
    });

Where

// From plugin source:
encodedStringToBytes: function(string) {
    var data = atob(string);
    var bytes = new Uint8Array(data.length);
    for (var i = 0; i < bytes.length; i++)
    {
        bytes[i] = data.charCodeAt(i);
    }
    return bytes;
},
bytesToEncodedString: function(bytes) {
    return btoa(String.fromCharCode.apply(null, bytes));
},

I hope this helps