问:
How to access the parent tab's url from a popup?
So I have a default_popup:popup.html defined in the manifest.json, from which I want to access the current tab that initiated the action. The tabId and the tab url are required. How do I go about doing it ?</p>

答:
I think this might help you:

http://code.google.com/chrome/extensions/tabs.html#method-getCurrent.

It returns the currently selected tab when you execute it (i.e. tab that initiated the action if you run it when the popup opens), and returns an object that contains the data you need.


来源: stackexchange

问:
Docker compose cant find package.json in path
I am trying to dockerize my node app but I can't seem to understand why it can't find the package.json file because the package.json file is in the same path as the docker compose and dockerfile. Here is the folder structure:

Below is the dockerfile:

Dockerfile

```<code>FROM node:12

# RUN mkdir -p ./usr/src/app/
COPY . /usr/src/app/

WORKDIR /usr/src/app/

# ADD package.json /usr/src/app/package.json
COPY package*.json ./

RUN yarn
RUN yarn global add pm2

COPY . .

EXPOSE 3005
EXPOSE 9200

CMD yarn start:dev
</code>```

And the docker compose file:

docker-compose.yml

```<code>version: "3.6"
services:
  api:
    image: node:12.13.0-alpine
    container_name: cont
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 3005:3005
    environment:
      - JWT_TOKEN_SECRET=ajsonwebtokensecret
      - MONGO_URI=mongodb://localhost:27017/em
      - PORT=3005
      - MAIL_USER=******
      - MAIL_PASS=******
      - FORGOT_PASS_EMAIL=noreply@em.com
      - CLIENT_SIDE_URL=http://localhost:3001
      - ELASTICSEARCH_URI=http://localhost:9200
   volumes:
      - .:/usr/src/app/
    command: yarn start:dev
    links:
      - elasticsearch
    depends_on:
      - elasticsearch
    networks:
      - esnet
  elasticsearch:
    container_name: em-elasticsearch
    image: docker.elastic.co/elasticsearch/elasticsearch:7.6.0
    volumes:
      - esdata:/usr/share/elasticsearch/data
    environment:
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - discovery.type=single-node
    logging:
      driver: none
    ports:
      - 9300:9300
      - 9200:9200
    networks:
      - esnet
volumes:
  esdata:
networks:
  esnet:
</code>```

When i try to run docker compose up i get this error

cont       | yarn run v1.19.1

cont       | error Couldn't find a package.json file in "/"

cont       | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this
  command.

cont exited with code 1

I have tried this, but all solutions I have tried don't work. Does anyone have a solution to this?

答:
Relative pathing. Note that the working COPY command is COPY . .. The . there means 'the current directory'. So what you need is:

```<code>COPY ./package*.json ./
</code>```

You would simplify your debugging by running docker build -t scratch . to eliminate docker-compose from the equation. Always drive it down to absolute minimal reproducer to isolate the exact issue.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to dockerize my node app but I can't seem to understand why it can't find the package.json file because the package.json file is in the same path as the docker compose and dockerfile. Here is the folder structure:

Below is the dockerfile:

Dockerfile

FROM node:12

# RUN mkdir -p ./usr/src/app/
COPY . /usr/src/app/

WORKDIR /usr/src/app/

# ADD package.json /usr/src/app/package.json
COPY package*.json ./

RUN yarn
RUN yarn global add pm2

COPY . .

EXPOSE 3005
EXPOSE 9200

CMD yarn start:dev

And the docker compose file:

docker-compose.yml

version: "3.6"
services:
  api:
    image: node:12.13.0-alpine
    container_name: cont
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 3005:3005
    environment:
      - JWT_TOKEN_SECRET=ajsonwebtokensecret
      - MONGO_URI=mongodb://localhost:27017/em
      - PORT=3005
      - MAIL_USER=******
      - MAIL_PASS=******
      - FORGOT_PASS_EMAIL=noreply@em.com
      - CLIENT_SIDE_URL=http://localhost:3001
      - ELASTICSEARCH_URI=http://localhost:9200
   volumes:
      - .:/usr/src/app/
    command: yarn start:dev
    links:
      - elasticsearch
    depends_on:
      - elasticsearch
    networks:
      - esnet
  elasticsearch:
    container_name: em-elasticsearch
    image: docker.elastic.co/elasticsearch/elasticsearch:7.6.0
    volumes:
      - esdata:/usr/share/elasticsearch/data
    environment:
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - discovery.type=single-node
    logging:
      driver: none
    ports:
      - 9300:9300
      - 9200:9200
    networks:
      - esnet
volumes:
  esdata:
networks:
  esnet:

When i try to run docker compose up i get this error

cont       | yarn run v1.19.1

cont       | error Couldn't find a package.json file in "/"

cont       | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this
  command.

cont exited with code 1

I have tried this, but all solutions I have tried don't work. Does anyone have a solution to this?

Body:
Relative pathing. Note that the working COPY command is COPY . .. The . there means 'the current directory'. So what you need is:

COPY ./package*.json ./

You would simplify your debugging by running docker build -t scratch . to eliminate docker-compose from the equation. Always drive it down to absolute minimal reproducer to isolate the exact issue.


问:
Picker with SegmentPickerStyle() doesn’t show picker title in SwiftUI
I created  a segment  picker for select gender in that segment picker I have to option one for Male and another for Female. Picker is working fine But set title on  with picker it’s not showing. I set title Select Gender which is not showing as a title on the Picker.

```<code>struct ManagerChildrenView: View {

        //MARK: Properties
        @State var selectedGender = 0
        let genders = ["Male", "Female"]

        var body: some View {

            Form{
                Section{
                    Picker("Select Gender", selection: $selectedGender) {

                        ForEach(0..<genders.count) { index in
                            Text(self.genders[index]).tag(index).font(.title)
                        }
                    }.pickerStyle(SegmentedPickerStyle())
                }
            }
        }
    }
</code>```

Screenshot:

答:
Label is not used for SegmentedPickerStyle. Instead you can use the following approach

```<code>HStack {
    Text("Select Gender")
    Picker("", selection: $selectedGender) {

        ForEach(0..<genders.count) { index in
            Text(self.genders[index]).tag(index).font(.title)
        }
    }.pickerStyle(SegmentedPickerStyle())
}
</code>```

Body:
I created  a segment  picker for select gender in that segment picker I have to option one for Male and another for Female. Picker is working fine But set title on  with picker it’s not showing. I set title Select Gender which is not showing as a title on the Picker.

struct ManagerChildrenView: View {

        //MARK: Properties
        @State var selectedGender = 0
        let genders = ["Male", "Female"]

        var body: some View {

            Form{
                Section{
                    Picker("Select Gender", selection: $selectedGender) {

                        ForEach(0..<genders.count) { index in
                            Text(self.genders[index]).tag(index).font(.title)
                        }
                    }.pickerStyle(SegmentedPickerStyle())
                }
            }
        }
    }

Screenshot:

Body:
Label is not used for SegmentedPickerStyle. Instead you can use the following approach

HStack {
    Text("Select Gender")
    Picker("", selection: $selectedGender) {

        ForEach(0..<genders.count) { index in
            Text(self.genders[index]).tag(index).font(.title)
        }
    }.pickerStyle(SegmentedPickerStyle())
}


问:
How can I get the data-id attribute?
I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.

How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.

$("#list li").on('click', function() {
  //  ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
  alert($(this).attr("#data-id"));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<ul id="list" class="grid">
  <li data-id="id-40" class="win">

      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />

  </li>
</ul></code>```

答:
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.</p>
```<code>$('#select').on('change', function(){
        let element = $("#visiabletoID");
        element.val($(this).find(':selected').data('record'));
    });
</code>```

Title: How can I get the data-id attribute?

Body:
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.

$('#select').on('change', function(){
        let element = $("#visiabletoID");
        element.val($(this).find(':selected').data('record'));
    });


问:
Is there a way to find a string in a list and print just the list element associated with that string?
I am working on an Employee Management System and would like my user to search for an employee by SSN. Once the employee is found, I'd like to print the list associated with that SSN. Eventually, I'd like to search for an employee by SSN and allow the user to edit the data in the fields as well. Right now, I can't figure out how to associate the SSN search to the list. I can find the SSN, but I don't know how to display it.  How do I do that?</p>

```<code>employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "FIND":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        if find_emp in employee_index:
</code>```

答:
Instead of a dict try using key pair values like this

```<code>mydict = {"SSN": 465736283, "Name": 'Some Dude'}
</code>```

But have it like this

```<code>{
    "employee": {
        "SSN": "1574083",
        "username": "gustog",
        "full_name": "Don Won",
        "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
        "bio": "This is my bio",
        "website": "http://donwon.gov",
        "counts": {
            "media": 1320,
            "follows": 420,
            "followed_by": 3410
        }
}
</code>```

This might let you store the info better and then retrieved it faster instead of looping over a array

Body:
I am working on an Employee Management System and would like my user to search for an employee by SSN. Once the employee is found, I'd like to print the list associated with that SSN. Eventually, I'd like to search for an employee by SSN and allow the user to edit the data in the fields as well. Right now, I can't figure out how to associate the SSN search to the list. I can find the SSN, but I don't know how to display it.  How do I do that?

employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "FIND":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        if find_emp in employee_index:

Body:
Instead of a dict try using key pair values like this

mydict = {"SSN": 465736283, "Name": 'Some Dude'}

But have it like this

{
    "employee": {
        "SSN": "1574083",
        "username": "gustog",
        "full_name": "Don Won",
        "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
        "bio": "This is my bio",
        "website": "http://donwon.gov",
        "counts": {
            "media": 1320,
            "follows": 420,
            "followed_by": 3410
        }
}

This might let you store the info better and then retrieved it faster instead of looping over a array


问:
Cannot fully scroll to first and last items with padding on both ends in recycler view
I have recycler view in a home fragment.

```<code>        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerViewSkills"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:clipToPadding="false"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3" />
</code>```

The Item in the recycler view has layout as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:padding="4dp">

        <androidx.cardview.widget.CardView
                android:id="@id/cardView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:cardElevation="4dp"
                android:clipToPadding="false"
                app:cardCornerRadius="8dp"
                app:contentPaddingLeft="48dp"
                app:contentPaddingRight="48dp"
                app:contentPaddingTop="24dp"
                app:contentPaddingBottom="24dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

            <ImageView
                    android:id="@+id/imageViewCategoryIcon"
                    android:layout_width="@dimen/category_card_icon_size_small"
                    android:layout_height="@dimen/category_card_icon_size_small"
                    android:adjustViewBounds="true" />

        </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/textViewCategoryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="2dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="2dp"
        android:ellipsize="end"
        android:gravity="center"
        android:lines="2"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="@+id/cardView"
        app:layout_constraintStart_toStartOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/cardView"
        tools:text="Communication" />

    <ImageView
            android:id="@+id/imageViewPremium"
            android:elevation="8dp"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/ribbon"
            android:visibility="gone"
            app:layout_constraintTop_toTopOf="@id/cardView"
            app:layout_constraintRight_toRightOf="@id/cardView"
            tools:visibility="visible" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

My problem is when I cannot fully scroll to the first or last item.

When I scroll to the end it looks like image below:

But when I leave it, it goes back to the position as shown below: Somehow when scroll horizontal the recycler view's padding on left and right doesn't work.

答: Setting both height and width of RecyclerView to 0dp worked for me. (when using constraintLayout)

Body:
I have recycler view in a home fragment.

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerViewSkills"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:clipToPadding="false"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3" />

The Item in the recycler view has layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:padding="4dp">

        <androidx.cardview.widget.CardView
                android:id="@id/cardView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:cardElevation="4dp"
                android:clipToPadding="false"
                app:cardCornerRadius="8dp"
                app:contentPaddingLeft="48dp"
                app:contentPaddingRight="48dp"
                app:contentPaddingTop="24dp"
                app:contentPaddingBottom="24dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

            <ImageView
                    android:id="@+id/imageViewCategoryIcon"
                    android:layout_width="@dimen/category_card_icon_size_small"
                    android:layout_height="@dimen/category_card_icon_size_small"
                    android:adjustViewBounds="true" />

        </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/textViewCategoryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="2dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="2dp"
        android:ellipsize="end"
        android:gravity="center"
        android:lines="2"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="@+id/cardView"
        app:layout_constraintStart_toStartOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/cardView"
        tools:text="Communication" />

    <ImageView
            android:id="@+id/imageViewPremium"
            android:elevation="8dp"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/ribbon"
            android:visibility="gone"
            app:layout_constraintTop_toTopOf="@id/cardView"
            app:layout_constraintRight_toRightOf="@id/cardView"
            tools:visibility="visible" />
</androidx.constraintlayout.widget.ConstraintLayout>

My problem is when I cannot fully scroll to the first or last item.

When I scroll to the end it looks like image below:

But when I leave it, it goes back to the position as shown below: Somehow when scroll horizontal the recycler view's padding on left and right doesn't work.


问:
Xamarin Forms saving image in sqlite database
How do I save an image I captured directly to sqlite(sqlite-net-pcl) database?

Here's my code but it can only save in "Internal Storage" of the phone.

private async void TakePhotoButton_Clicked(object sender, EventArgs e)
{
    try
    {
        await CrossMedia.Current.Initialize();
        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await DisplayAlert("No Camera", "No Camera Available", "OK");
            return;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(
        new StoreCameraMediaOptions
        {
            SaveToAlbum = true,
            //Directory = "Sample",
            //Name = "Test.jpg"
        });

        if (file == null)
            return;

        PathLabel.Text = file.AlbumPath;
        MainImage.Source = ImageSource.FromStream(() =>
        {
            var stream = file.GetStream();
            file.Dispose();
            return stream;

        });
    }
    catch (Exception ex)
    {
        await DisplayAlert("error", ex.ToString(), "OK");
    }

}
```

答:
Concerning the SaveToAlbum option

This will restult in 2 photos being saved for the photo. One in your private folder and one in a public directory that is shown. The value will be returned at AlbumPath. (Source)

Unless you really need the photo in the camera roll, there is no need to use SaveToAlbum.

Anyway, the file is still saved to your apps sandbox (the part of the devices storage that is reserved exclusively for your app) and you can retrieve the path with file.Path.

Having said that, it's easy to obtain the binary data representing your image

await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
    await DisplayAlert("No Camera", "No Camera Available", "OK");
    return;
}

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions());

if (file == null)
    return;

var imageData = File.ReadAllBytes(file.Path);
```

<p>Obviously (see here and here) it's possibly to store binary data (<em>BLOB</em>s) in an SQLite database. The simplest conceivable model to store an image in the database would be something like</p>

<pre class="lang-cs prettyprint-override"><code>class Image
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public byte[] Data { get; set; }
}
</code>```

Assuming that _imageRepository is your repository abstraction you are saving the images in, the data could be saved as

```<code>// ...
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions());

if (file == null)
    return;

var imageData = File.ReadAllBytes(file.Path);

_imageRepository.Add(new Image()
                         {
                             Data = imageData
                         });

</code>```

Later on, to display the image, you can get the Image from the repository and use the Data property, e.g. by passing it to a MemoryStream (if you need a stream)

// example: Loading by ID, loading all images is conceivable, too
var image = _imageRepository.LoadImage(id);
ImageControl.ImageSource = ImageSource.FromStream(() => new MemoryStream(image.Data));
```

Body:
Concerning the SaveToAlbum option

This will restult in 2 photos being saved for the photo. One in your private folder and one in a public directory that is shown. The value will be returned at AlbumPath. (Source)

Unless you really need the photo in the camera roll, there is no need to use SaveToAlbum.

Anyway, the file is still saved to your apps sandbox (the part of the devices storage that is reserved exclusively for your app) and you can retrieve the path with file.Path.

Having said that, it's easy to obtain the binary data representing your image

await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
    await DisplayAlert("No Camera", "No Camera Available", "OK");
    return;
}

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions());

if (file == null)
    return;

var imageData = File.ReadAllBytes(file.Path);

Obviously (see here and here) it's possibly to store binary data (BLOBs) in an SQLite database. The simplest conceivable model to store an image in the database would be something like

class Image
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public byte[] Data { get; set; }
}

Assuming that _imageRepository is your repository abstraction you are saving the images in, the data could be saved as

// ...
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions());

if (file == null)
    return;

var imageData = File.ReadAllBytes(file.Path);

_imageRepository.Add(new Image()
                         {
                             Data = imageData
                         });

Later on, to display the image, you can get the Image from the repository and use the Data property, e.g. by passing it to a MemoryStream (if you need a stream)

// example: Loading by ID, loading all images is conceivable, too
var image = _imageRepository.LoadImage(id);
ImageControl.ImageSource = ImageSource.FromStream(() => new MemoryStream(image.Data));


问:
Error cannot find symbol, method getcustomerdiscount()
Having an issue on line 192 in netbeans
cannot seem to figure out were the issue is

```
Line 192: System.out.println("Percent off: "+customer.getcustomerDiscount());

Error:
cannot find symbol
symbol: method getcustomerDiscount()
location: variable customer of type Customer
```

(PS yes i know it's in 1 java file, it's supposed to be)

```<code>package Driver2;

import java.util.Scanner;
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Person{
private String name;
private String address;
private String number;
private int customerPurchase;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
private int customerPurchase = 0;
private int customerDiscount;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors

//@Override
//public int getcustomerPurchase()
//{
//    return this.customerPurchase;
//}

public int getcustomerDiscount()
{
    return this.customerDiscount;
}

//Mutators
/*
@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver3
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}
</code>```

Additional
I am a little confused, i called the driver 1 and even made an object and couldent get it to work also another question popped up when i tested the if else statement another way

Question Should i leave the if else statement inside the setter? or put into the getter? i think i have an issue were i am not retrieving a string because it is all set as a INT

答:
You are trying to call getcustomerDiscount on a Customer object. The method is not defined on this class but on Driver1.

Also: You should try to use Java naming conventions, in this case getcustomerDiscount and setcustomerDiscount should be renamed to getCustomerDiscount and setCustomerDiscount respectively.

Body:
Having an issue on line 192 in netbeans
cannot seem to figure out were the issue is

Line 192: System.out.println("Percent off: "+customer.getcustomerDiscount());

Error:
cannot find symbol
symbol: method getcustomerDiscount()
location: variable customer of type Customer

(PS yes i know it's in 1 java file, it's supposed to be)

package Driver2;

import java.util.Scanner;
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Person{
private String name;
private String address;
private String number;
private int customerPurchase;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
private int customerPurchase = 0;
private int customerDiscount;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors

//@Override
//public int getcustomerPurchase()
//{
//    return this.customerPurchase;
//}

public int getcustomerDiscount()
{
    return this.customerDiscount;
}

//Mutators
/*
@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver3
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}

Additional
I am a little confused, i called the driver 1 and even made an object and couldent get it to work also another question popped up when i tested the if else statement another way

Question Should i leave the if else statement inside the setter? or put into the getter? i think i have an issue were i am not retrieving a string because it is all set as a INT


问:
Identifying a dateformat and change it into another
I am working with the following piece of data which has a different format of dates and which creates confusion later in the process. The data is like:

S. No        DateTime               Area
1         03/05/2019 6:33            A
2         06/03/2019 07:23:45 AM     B```
</div>
</div>
</p>

<p>The first row is the format %m/%d/%Y h: mm and the second row is the format of %d/%m/%Y hh:mm: ss AM/PM. The first date value can be confusing though, is it 5th march or 3rd May. So to make everything of the same format, I want that my code detects the date format and changes in the desired format.</p>

<p>I have tried doing this:</p>

```
df['Detection Date'] = pd.to_datetime(df['Detection Date & Time'], errors = 'coerce').dt.datetime
col = df['Detection Date'].apply(str)

for i in df.index:
    if datetime.datetime.strptime(col, '%m/%d/%Y h:mm'):
       ColDate = datetime.datetime.strftime(col, '%d/%m/%Y hh:mm:ss AM/PM')
```

<p>But i am getting an error saying:</p>

<pre class="lang-py prettyprint-override"><code>TypeError: strptime() argument 1 must be str, not Series

</code>```

How it should be conducted.

Thanks

答:
You can specify both possible formats in to_datetime, so if format not match is returned missing values, so is possible use Series.fillna:

```<code>date1 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%m/%d/%Y %H:%M')
date2 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%d/%m/%Y %H:%M:%S %p')

df['DateTime'] = date1.fillna(date2)
print (df)
   S. No            DateTime Area
0      1 2019-03-05 06:33:00    A
1      2 2019-03-06 07:23:45    B
</code>```

Last if want specify new format add Series.dt.strftime - advanatage of solution are verify both formats:

```<code>df['DateTime'] = date1.fillna(date2).dt.strftime('%d/%m/%Y %H:%M:%S %p')
print (df)
   S. No                DateTime Area
0      1  05/03/2019 06:33:00 AM    A
1      2  06/03/2019 07:23:45 AM    B
</code>```

Details:

```<code>print (date1)
0   2019-03-05 06:33:00
1                   NaT
Name: DateTime, dtype: datetime64[ns]

print (date2)
0                   NaT
1   2019-03-06 07:23:45
Name: DateTime, dtype: datetime64[ns]
</code>```

Another possible solution without verify another formats - only repalaced format %m/%d/%Y %H:%M to %d/%m/%Y %H:%M:%S %p:

```<code>date1 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%m/%d/%Y %H:%M').dt.strftime('%d/%m/%Y %H:%M:%S %p')

df['DateTime'] = date1.replace('NaT', df['DateTime'])
print (df)
   S. No                DateTime Area
0      1  05/03/2019 06:33:00 AM    A
1      2  06/03/2019 07:23:45 AM    B
</code>```

Body:
I am working with the following piece of data which has a different format of dates and which creates confusion later in the process. The data is like:

S. No        DateTime               Area
1         03/05/2019 6:33            A
2         06/03/2019 07:23:45 AM     B

The first row is the format %m/%d/%Y h: mm and the second row is the format of %d/%m/%Y hh:mm: ss AM/PM. The first date value can be confusing though, is it 5th march or 3rd May. So to make everything of the same format, I want that my code detects the date format and changes in the desired format.

I have tried doing this:

df['Detection Date'] = pd.to_datetime(df['Detection Date & Time'], errors = 'coerce').dt.datetime
col = df['Detection Date'].apply(str)

for i in df.index:
    if datetime.datetime.strptime(col, '%m/%d/%Y h:mm'):
       ColDate = datetime.datetime.strftime(col, '%d/%m/%Y hh:mm:ss AM/PM')

But i am getting an error saying:

TypeError: strptime() argument 1 must be str, not Series

How it should be conducted.

Thanks

Body:
You can specify both possible formats in to_datetime, so if format not match is returned missing values, so is possible use Series.fillna:

date1 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%m/%d/%Y %H:%M')
date2 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%d/%m/%Y %H:%M:%S %p')

df['DateTime'] = date1.fillna(date2)
print (df)
   S. No            DateTime Area
0      1 2019-03-05 06:33:00    A
1      2 2019-03-06 07:23:45    B

Last if want specify new format add Series.dt.strftime - advanatage of solution are verify both formats:

df['DateTime'] = date1.fillna(date2).dt.strftime('%d/%m/%Y %H:%M:%S %p')
print (df)
   S. No                DateTime Area
0      1  05/03/2019 06:33:00 AM    A
1      2  06/03/2019 07:23:45 AM    B

Details:

print (date1)
0   2019-03-05 06:33:00
1                   NaT
Name: DateTime, dtype: datetime64[ns]

print (date2)
0                   NaT
1   2019-03-06 07:23:45
Name: DateTime, dtype: datetime64[ns]

Another possible solution without verify another formats - only repalaced format %m/%d/%Y %H:%M to %d/%m/%Y %H:%M:%S %p:

date1 = pd.to_datetime(df['DateTime'], errors = 'coerce', format='%m/%d/%Y %H:%M').dt.strftime('%d/%m/%Y %H:%M:%S %p')

df['DateTime'] = date1.replace('NaT', df['DateTime'])
print (df)
   S. No                DateTime Area
0      1  05/03/2019 06:33:00 AM    A
1      2  06/03/2019 07:23:45 AM    B


答:
You can parse through every employee in the list, and if employee[1] == find_emp i.e. if the serial number matches, you can print the employee's details.

```<code>elif add_new == "FIND":
    find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
    found = False
    for employee in employee_info:
        if employee[1] == find_emp:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')
            found = True

    if found == False:
        print("Employee not found!")
</code>```

If the employee is not found, you print the appropriate error message.

Title: Is there a way to find a string in a list and print just the list element associated with that string?

Body:
You can parse through every employee in the list, and if employee[1] == find_emp i.e. if the serial number matches, you can print the employee's details.

elif add_new == "FIND":
    find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
    found = False
    for employee in employee_info:
        if employee[1] == find_emp:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')
            found = True

    if found == False:
        print("Employee not found!")

If the employee is not found, you print the appropriate error message.


问:
how to create an array of custom class that contains generics in Java
I have an assignment where the goal is to create a HashTable implementation with generic keys and values. To handle collisions, we were told to use separate chaining. So, I tried doing this:

```<code>public class HashTable<K, V> implements Table<K, V> {

    private Node[] generics;

    public class Node {

        V value;
        Node next;

        public Node(V val) {
            value = val;
        }

    }

    public HashTable(int size) {
        generics = (Node[]) new Object[size];
    }

}
</code>```

For the separate chaining, I wanted to use a linked list implementation (what else), which is why I need generics to hold Node's, not just V's. The reason I cannot just write generics = new Node[size]; is that the Node class contains a generic, and generic array creation is not allowed. For this assignment, this workaround, which produces an "unchecked cast" warning, is acceptable.

Then, in the driver, it tries Table<String, String> ht = new HashTable<String, String>(5); and gets a ClassCastException. There was no ClassCastException when generics was a V[], for context.

So, my question is: How do I create a custom class array, where the custom class contains generics (without changing the driver)?

答:
Try below solution

```<code>public class HashTable<K, V> {
    private Node<V>[] generics;

    static class Node<V> {
        V value;
        Node next;
        public Node(V val) {
            value = val;
        }
    }
    private HashTable(int size) {
        generics = (Node<V>[]) new Node[size];
    }
}
</code>```

generics = (Node[]) new Node[size]; this line will give you unchecked cast warning for this code impl check HashMap source code

And if you want to remove unchecked cast warning than you wildcard in generic type reference

```<code> public class HashTable<K, V> {
    private Node<?>[] generics;

    static class Node<V> {
        V value;
        Node next;
        public Node(V val) {
            value = val;
        }
    }
    public HashTable(int size) {
        generics = new Node<?>[size];
    }
 }
</code>```

it will not give you any "unchecked cast" warning. for this you can HashTable source code

Body:
I have an assignment where the goal is to create a HashTable implementation with generic keys and values. To handle collisions, we were told to use separate chaining. So, I tried doing this:

public class HashTable<K, V> implements Table<K, V> {

    private Node[] generics;

    public class Node {

        V value;
        Node next;

        public Node(V val) {
            value = val;
        }

    }

    public HashTable(int size) {
        generics = (Node[]) new Object[size];
    }

}

For the separate chaining, I wanted to use a linked list implementation (what else), which is why I need generics to hold Node's, not just V's. The reason I cannot just write generics = new Node[size]; is that the Node class contains a generic, and generic array creation is not allowed. For this assignment, this workaround, which produces an "unchecked cast" warning, is acceptable.

Then, in the driver, it tries Table<String, String> ht = new HashTable<String, String>(5); and gets a ClassCastException. There was no ClassCastException when generics was a V[], for context.

So, my question is: How do I create a custom class array, where the custom class contains generics (without changing the driver)?

Body:
Try below solution

public class HashTable<K, V> {
    private Node<V>[] generics;

    static class Node<V> {
        V value;
        Node next;
        public Node(V val) {
            value = val;
        }
    }
    private HashTable(int size) {
        generics = (Node<V>[]) new Node[size];
    }
}

generics = (Node[]) new Node[size]; this line will give you unchecked cast warning for this code impl check HashMap source code

And if you want to remove unchecked cast warning than you wildcard in generic type reference

 public class HashTable<K, V> {
    private Node<?>[] generics;

    static class Node<V> {
        V value;
        Node next;
        public Node(V val) {
            value = val;
        }
    }
    public HashTable(int size) {
        generics = new Node<?>[size];
    }
 }

it will not give you any "unchecked cast" warning. for this you can HashTable source code


问:
How can I remotely connect to a JanusGraph server?
I want to use Java API to manipulate graph on a remote server, the server actually hosts in localhost. The code I use to connect server is:

```<code>JanusGraphFactory.Builder b = JanusGraphFactory.build();
b.set("hosts", "[localhost]");
JanusGraph graph = b.open();
</code>```

But after I run the program, it throws exception like this:

Exception in thread "main" java.lang.IllegalStateException: Need to set configuration value: root.storage.backend

So how can I connect to a remote JanusGraph server using Java API?

答:
Use the following code:</p>

```<code>        JanusGraphFactory.Builder config = JanusGraphFactory.build();
        config.set("storage.backend", "cassandrathrift");
        config.set("storage.cassandra.keyspace", "graph1");
        config.set("storage.hostname", "127.0.0.1");

        JanusGraph graph = config.open();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to use Java API to manipulate graph on a remote server, the server actually hosts in localhost. The code I use to connect server is:

JanusGraphFactory.Builder b = JanusGraphFactory.build();
b.set("hosts", "[localhost]");
JanusGraph graph = b.open();

But after I run the program, it throws exception like this:

Exception in thread "main" java.lang.IllegalStateException: Need to set configuration value: root.storage.backend

So how can I connect to a remote JanusGraph server using Java API?

Body:
Use the following code:

        JanusGraphFactory.Builder config = JanusGraphFactory.build();
        config.set("storage.backend", "cassandrathrift");
        config.set("storage.cassandra.keyspace", "graph1");
        config.set("storage.hostname", "127.0.0.1");

        JanusGraph graph = config.open();


问:
Xcode 10.1 - "IB Designables. Failed to render and update auto layout status". The agent crashed
I have an issue where my storyboard failed to render the layout, so I can't add constraints and also can't see the layout of my viewController.

How can I resolve this?

答:
All the previous answers did not help, but I figured it out.

In the @IBInspectable didSet property I was calling the common setup() function to utilize my view. However, I was trying to adjust a textField without checking whether it was nil or not. That's why I was getting "failed to render" problem and also a run time crash.

For example:

```<code>@IBInspectable var isTitleEnabled: Bool = true{
    didSet{ setup() }
}
</code>```

And the setup() function was:

```<code>private func setup(){
    textField.isSecureTextEntry = isPassword
}
</code>```

which is wrong. Xcode doesn't allow the subviews to be modified in this way.

When the Interface Builder (IB) component is rendered, Xcode thinks that it is not initialized yet, so it raises an error. To solve this misunderstanding, we need to make sure that the Interface Builder component is not nil.

So, instead we need to use it like that:

```<code>guard textField != nil else { return }
textField.isSecureTextEntry = isPassword ? true : false
</code>```

The Interface Builder component don't need only to be a UITextField. It is valid for other Interface Builder components like UILabel, UIImageView, etc.

Body:
All the previous answers did not help, but I figured it out.

In the @IBInspectable didSet property I was calling the common setup() function to utilize my view. However, I was trying to adjust a textField without checking whether it was nil or not. That's why I was getting "failed to render" problem and also a run time crash.

For example:

@IBInspectable var isTitleEnabled: Bool = true{
    didSet{ setup() }
}

And the setup() function was:

private func setup(){
    textField.isSecureTextEntry = isPassword
}

which is wrong. Xcode doesn't allow the subviews to be modified in this way.

When the Interface Builder (IB) component is rendered, Xcode thinks that it is not initialized yet, so it raises an error. To solve this misunderstanding, we need to make sure that the Interface Builder component is not nil.

So, instead we need to use it like that:

guard textField != nil else { return }
textField.isSecureTextEntry = isPassword ? true : false

The Interface Builder component don't need only to be a UITextField. It is valid for other Interface Builder components like UILabel, UIImageView, etc.


问:
Connect-AzAccount Powershell on-prem
I am new to Azure and I've successfully installed PowerShell on my macOS. Now I want to run get-azvm command and stop/delete a vm from on-prem (not cloud shell).

First thing I did from Terminal:
1. PWSH to launch PowerShell
2. Connect-AzAccount, browser opens to authenticate and I get an error:

Connect-AzAccount xx: Device authentication is required.
Trace ID: xx
Correlation ID: xx
+ CategoryInfo          : CloseError: (:) [Connect-AzAccount], AadAuthenticationFailedException

I continue with az login command. Result:
You have logged in. Now let us find all the subscriptions to which you have access...

{
}

I run: get-azvm and get another error:
get-azvm : No subscription found in the context.  Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Connect-AzAccount to login.
At line:1 char:1

Please, what am I doing wrong? Do I need to register my on-prem machine somewhere?

Thanks for the help.

答:
According to the error from Connect-AzAccount, Looks your account is MFA-enabled, please use the authentication methods to authenticate. Or you can create a service principal, assign a role for it in the subscription, then you can login with the service principal and use it to Get-AzVM, details here.

I continue with az login command. Result: You have logged in. Now let us find all the subscriptions to which you have access..

You should note, Connect-AzAccount is used to login the Azure Powershell, az login is used to login the Azure CLI, they are different. From the output, looks you logged in successfully in Azure CLI, you could use az account set --subscription <subscription-id> to set the subscription which you want to get the VMs from, then use az vm list to list VMs.

Title: Connect-AzAccount Powershell on-prem


问:
System.InvalidOperationException: IDX20803 when validating Azure AD token
I have a SPA client in Angular which logs into Azure AD successfully and generates a token which I then pass it to the .Net Core(3.0) API via Authorization: Bearer ${token}  I then try to validate the token with [Authorize] to check and then allow access to the REST Api calls, we are still using "ver": "1.0" and there is no nonce in the JWT header. I have the below code in ConfigureServices method:

```<code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {
                   options.Authority = "https://login.microsoftonline.com/common";
                   options.RequireHttpsMetadata = false;
                   options.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuer = true,
                       ValidIssuer = options.Authority,
                       ValidateLifetime = true,
                       ValidateAudience = true,
                       ValidAudience = "{myClientID}",
                       IssuerValidator = (issuer, token, parameter) => "https://sts.windows.net/{MyIssuer}/"
                   };
               });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy =
                     new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            });
</code>```

When I run the project with locahost, it works fine, but I deploy the code to a server, I got the below error message :

```<code>Exception occurred while processing message.

Exception:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login.microsoftonline.com/common/.well-known/openid-configuration'.
 ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'https://login.microsoftonline.com/common/.well-known/openid-configuration'.
 ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it.
 ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
</code>```

The above message indicates that something is not allowing me to connect to the site to validate, are my parameters correct? I used jwt.io to check the token and it says the Signature is valid and on the body I get to see the values I expect for "aud:","iss:" "amr":["pwd"] etc. I am new to Azure AD and token validation, so please bear with me. Is there anything I am missing? Thank you

答:
That error is caused by the app being unable to connect to the Azure AD metadata endpoint.
It needs to load configuration from there at the start, including public keys that the app can use to verify token signatures.

Either something is blocking the connection (like a firewall), or Azure AD is down (extremely unlikely).

Body:
I have a SPA client in Angular which logs into Azure AD successfully and generates a token which I then pass it to the .Net Core(3.0) API via Authorization: Bearer ${token}  I then try to validate the token with [Authorize] to check and then allow access to the REST Api calls, we are still using "ver": "1.0" and there is no nonce in the JWT header. I have the below code in ConfigureServices method:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {
                   options.Authority = "https://login.microsoftonline.com/common";
                   options.RequireHttpsMetadata = false;
                   options.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuer = true,
                       ValidIssuer = options.Authority,
                       ValidateLifetime = true,
                       ValidateAudience = true,
                       ValidAudience = "{myClientID}",
                       IssuerValidator = (issuer, token, parameter) => "https://sts.windows.net/{MyIssuer}/"
                   };
               });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy =
                     new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            });

When I run the project with locahost, it works fine, but I deploy the code to a server, I got the below error message :

Exception occurred while processing message.

Exception:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login.microsoftonline.com/common/.well-known/openid-configuration'.
 ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'https://login.microsoftonline.com/common/.well-known/openid-configuration'.
 ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it.
 ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---

The above message indicates that something is not allowing me to connect to the site to validate, are my parameters correct? I used jwt.io to check the token and it says the Signature is valid and on the body I get to see the values I expect for "aud:","iss:" "amr":["pwd"] etc. I am new to Azure AD and token validation, so please bear with me. Is there anything I am missing? Thank you


问:
Application context loading twice
I am writing a web application with Struts 3 using Tomcat 7 with Eclipse. When I launch Tomcat, it seems the context is loaded twice (log file shows that applicationContext.xml is read twice).

I have a context.xml file under src/main/webapp/META-INF for Tomcat :

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbname" docBase="dbname" reloadable="true" debug="1">
  <Resource name="jdbc/dbname"
            username="dbusername"
            password="dbpassword"
            auth="Container"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/dbname"
            type="javax.sql.DataSource"
            initialSize="5"
            maxActive="120"
            maxIdle="5"
            maxWait="5000"
            poolPreparedStatements="true"
            validationQuery="select 1" />
</Context>
</code>```

My server.xml declares also (under Host and Engine) :

```<code><Context docBase="dbname" path="/dbname" source="org.eclipse.jst.jee.server:dbname"/>
</code>```

Without this, Tomcat does not launch the application.

In web.xml, I declare the contextConfigLocation like this :

```<code><context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
</code>```

applicationContext.xml is located under src/main/resources/spring

Those are the two lines from the log file showing the reload :

```<code>2012-10-14 00:17:08,191 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'name': initialization completed in 438 ms
2012-10-14 00:17:10,972 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Closing WebApplicationContext for namespace 'name-servlet': startup date [Sun Oct 14 00:17:07 CEST 2012]; parent: Root WebApplicationContext
</code>```

Issue is that on the second reload, it fails because Spring can't find any data source (although one is definitely defined since Spring finds it during the first boot)

答:
To prevent this, we have to set autoDeploy=”false” and deployOnStartup=”false” in the  tag:</p>

```<code><Host name="localhost" appBase="webapps" unpackWARs="true"
  autoDeploy="false" deployOnStartup="false">
    <Context path="" docBase="ExampleApp"></Context>

    <!-- Further settings for localhost -->
</Host>
</code>```

Title: Application context loading twice

Body:
I am writing a web application with Struts 3 using Tomcat 7 with Eclipse. When I launch Tomcat, it seems the context is loaded twice (log file shows that applicationContext.xml is read twice).

I have a context.xml file under src/main/webapp/META-INF for Tomcat :

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbname" docBase="dbname" reloadable="true" debug="1">
  <Resource name="jdbc/dbname"
            username="dbusername"
            password="dbpassword"
            auth="Container"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/dbname"
            type="javax.sql.DataSource"
            initialSize="5"
            maxActive="120"
            maxIdle="5"
            maxWait="5000"
            poolPreparedStatements="true"
            validationQuery="select 1" />
</Context>

My server.xml declares also (under Host and Engine) :

<Context docBase="dbname" path="/dbname" source="org.eclipse.jst.jee.server:dbname"/>

Without this, Tomcat does not launch the application.

In web.xml, I declare the contextConfigLocation like this :

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>

applicationContext.xml is located under src/main/resources/spring

Those are the two lines from the log file showing the reload :

2012-10-14 00:17:08,191 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'name': initialization completed in 438 ms
2012-10-14 00:17:10,972 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Closing WebApplicationContext for namespace 'name-servlet': startup date [Sun Oct 14 00:17:07 CEST 2012]; parent: Root WebApplicationContext

Issue is that on the second reload, it fails because Spring can't find any data source (although one is definitely defined since Spring finds it during the first boot)

Body:
To prevent this, we have to set autoDeploy=”false” and deployOnStartup=”false” in the  tag:

<Host name="localhost" appBase="webapps" unpackWARs="true"
  autoDeploy="false" deployOnStartup="false">
    <Context path="" docBase="ExampleApp"></Context>

    <!-- Further settings for localhost -->
</Host>


问:
How to send 'Some' with argument in a function
I am trying to send the result of a match to a function Foo, but the result of the match is type Some()

How can I send it as an argument to the Foo function?

```<code>struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let mut x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }
}
</code>```

答:
I think the problem with the existing code is that Foo consumes an Option, while your match gets a reference to an Option. They need to match. There's a few approaches that will work here.

Make Foo and the match both use values. This means you remove the ref on the match pieces. You wont be able to use the Person value after the match, since it will have been chopped into its component pieces.

```<code>fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: a @ Some(_),
            lastname: b @ _,
        }) => Foo(a),
        _ => {}
    }

</code>```

Make Foo and the match both use references. You keep the ref on the match, but add an & to Foo's argument.

```<code>fn Foo(x: &Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }

</code>```

Clone a before passing it to Foo. Foo and the match pattern don't change, but the way you call Foo changes slightly

```<code>fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a.clone()),
        _ => {}
    }

</code>```

Of course, in your particular case you dont need to use pattern matching at all, you could just use some of the tools that already exist in Option, such as map.

```<code>x.map(|p| Foo(p.name));
</code>```

Body:
I am trying to send the result of a match to a function Foo, but the result of the match is type Some()

How can I send it as an argument to the Foo function?

struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let mut x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }
}

Body:
I think the problem with the existing code is that Foo consumes an Option, while your match gets a reference to an Option. They need to match. There's a few approaches that will work here.

Make Foo and the match both use values. This means you remove the ref on the match pieces. You wont be able to use the Person value after the match, since it will have been chopped into its component pieces.

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: a @ Some(_),
            lastname: b @ _,
        }) => Foo(a),
        _ => {}
    }

Make Foo and the match both use references. You keep the ref on the match, but add an & to Foo's argument.

fn Foo(x: &Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }

Clone a before passing it to Foo. Foo and the match pattern don't change, but the way you call Foo changes slightly

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

// ...

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a.clone()),
        _ => {}
    }

Of course, in your particular case you dont need to use pattern matching at all, you could just use some of the tools that already exist in Option, such as map.

x.map(|p| Foo(p.name));


问:
Can you print $ in Scala string interpolation?
In Scala, I want to print the price of some item with string interpolation. Is it possible to display the $ character with interpolation?
This works:

```<code>scala> println(s"It only costs ${3 + 4} dollars")
It only costs 7 dollars
</code>```

So why does this not work? It should still say $7, according to the docs

```<code>scala> println(s"It only costs $${3 + 4}")
It only costs ${3 + 4}
</code>```

答:
You need a third $ to the actual interpolation too. The following should work:

```<code> s"It only costs $$${3 + 4} dollars"
</code>```

The first two $s are for the $ sign in the output, the third is for the interpolation. It might be easier to see this way:

```<code> s"It only costs $$ ${3 + 4} dollars"
</code>```

Body:
In Scala, I want to print the price of some item with string interpolation. Is it possible to display the $ character with interpolation?
This works:

scala> println(s"It only costs ${3 + 4} dollars")
It only costs 7 dollars

So why does this not work? It should still say $7, according to the docs

scala> println(s"It only costs $${3 + 4}")
It only costs ${3 + 4}

Body:
You need a third $ to the actual interpolation too. The following should work:

 s"It only costs $$${3 + 4} dollars"

The first two $s are for the $ sign in the output, the third is for the interpolation. It might be easier to see this way:

 s"It only costs $$ ${3 + 4} dollars"


问:
Passing the value from the form to another page
```<code>def get_name(request):
    if request.method == 'POST':
        user_code = generate_code(8)
        subject = 'ver code'
        message = user_code
        phone = request.POST['phone']
        form = NameForm(request.POST)
        if form.is_valid():
            Registration.objects.create(fio=request.POST['fio'],mail=request.POST['mail'],code=user_code)
            send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False)

        return HttpResponseRedirect('endreg')
    else:
        form = NameForm()
    return render(request, 'registers/detail.html', {'form': form})

def endreg(request):
    if request.method == 'POST':
        form = NameForm1(request.POST)
        if form.is_valid():
            code_use = form.cleaned_data.get("key")
            try:
                user = Registration.objects.get(code=code_use)
                user.verification = True
                user.save()
                messages.warning(request, u'thanks.')
            except:
                messages.warning(request, u'error.')
    else:
        form = NameForm1()
    return render(request, 'registers/endreg.html', {'form': form})
</code>```

I have 2 fields in the form. when you submit the form to the server, a random confirmation code is generated and sent to this mail
how on page 2, where is the code input field, display to which mail it was sent?
1 page detail
2 page endreg.
how to send the sender email to the endreg page?

答:
You can use django sessions. It can store the data.
https://docs.djangoproject.com/en/3.0/topics/http/sessions/</p>

```<code>def fun(request):
    # this is the function where we setting the key value in session
    request.session["name"] ="your name"
    return HttpResponse("Response here")`
</code>```

```<code>def fun2(request):
    # this is the function where we getting the session key value
    name = request.session.get("name", " ")
    return HttpResponse("Response here")
</code>```

Body:
def get_name(request):
    if request.method == 'POST':
        user_code = generate_code(8)
        subject = 'ver code'
        message = user_code
        phone = request.POST['phone']
        form = NameForm(request.POST)
        if form.is_valid():
            Registration.objects.create(fio=request.POST['fio'],mail=request.POST['mail'],code=user_code)
            send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False)

        return HttpResponseRedirect('endreg')
    else:
        form = NameForm()
    return render(request, 'registers/detail.html', {'form': form})

def endreg(request):
    if request.method == 'POST':
        form = NameForm1(request.POST)
        if form.is_valid():
            code_use = form.cleaned_data.get("key")
            try:
                user = Registration.objects.get(code=code_use)
                user.verification = True
                user.save()
                messages.warning(request, u'thanks.')
            except:
                messages.warning(request, u'error.')
    else:
        form = NameForm1()
    return render(request, 'registers/endreg.html', {'form': form})

I have 2 fields in the form. when you submit the form to the server, a random confirmation code is generated and sent to this mail
how on page 2, where is the code input field, display to which mail it was sent?
1 page detail
2 page endreg.
how to send the sender email to the endreg page?

Body:
You can use django sessions. It can store the data.
https://docs.djangoproject.com/en/3.0/topics/http/sessions/

def fun(request):
    # this is the function where we setting the key value in session
    request.session["name"] ="your name"
    return HttpResponse("Response here")`

def fun2(request):
    # this is the function where we getting the session key value
    name = request.session.get("name", " ")
    return HttpResponse("Response here")


问:
In db2 on cloud Lite version, is it possible to export sql query results to csv? How?
How do I export results of an sql query as a csv using db2 on cloud Lite version?  Is it possible, or is a paid level required for this?   I found the link in the results field “export to csv” but when I clicked on it, nothing happened.  Similarly, in the query field on the left side of the screen there is a link to export to csv, but that didn’t work either.  I would like to export to a form that can be used in WEKA.    </p>

答:
I have a Db2 on Cloud Lite and I can confirm that it works. I am using the Run SQL dialog to query the database. The button to actually run a query is a dropdown where you can choose to run the selected statement and export the result to a CSV or XLSX (Excel) file.

The export action is handled like a regular download. Depending on the browser you may see a pop-up or just a file in your download directory.


问:
What is the best way to read a JSON file and obtain the values without the invisible characters in Python?
I have a simple JSON file that I was supposed to use as a configuration file, it contains the default directories for whoever is running the script using their MacBooks:

```<code>{
  "main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
  "reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
}
</code>```

I read the JSON file and obtain the values using this code:

```<code>with open('reportconfig.json','r') as j:
    config_data = json.load(j)

main_sheet_path = str(config_data.get('main_sheet_path'))
reference_sheet_path = str(config_data.get('reference_sheet_path'))
</code>```

I use the path to check for a source file's existence before doing anything with it:

```<code>source_file = 'source.xlsx'
source_file = main_sheet_path + filename
if not os.path.isfile(source_file) :
    print ('ERROR: Source file \'' + source_file + '\' NOT FOUND!')
    return
</code>```

Note that the filename is inputted as a parameter when the script is run (there are multiple files, the script has to know which one to target).

The file is there for sure but the script never seems to "see" it so I get that "ERROR" that I printed in the above code. Why do I think there are invisible characters? Because when I copy and paste from what was printed in the "error" notice above into the terminal, the last few characters of the file name always gets substituted by some invisible characters and hitting backspace erases characters where the cursor isn't supposed to be.

How do I know for sure that the file is there and that my problem is with reading the JSON file and not in the Directory names or anywhere else in the code? Because I finally gave up on using a JSON config file and went with a configuration file like this instead:

```<code>#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
file_paths = { "main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
               "reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
             }
</code>```

I then just import the file and obtain the values like this:

```<code>import reportconfig as cfg
main_sheet_path = cfg.file_paths['main_sheet_path']
reference_sheet_path = cfg.file_paths['reference_sheet_path']
...
</code>```

This workaround works perfectly — I don't get the "error" that the file isn't there when it is and the rest of the script is executed as expected. When the file isn't there, I get the proper "error" I expect and copying-and-pasting the full path and filename from the "error message" gives me the complete file name and hitting the backspace erases the right characters (no funny behavior, no invisible characters).

But could anyone please tell me how read the JSON file properly without getting those pesky invisible characters? I've spent hours trying to figure it out including searching seemingly related questions in stackoverflow but couldn't find the answer. TIA!

答:
I think there is just a typo error in this code:
   source_file = 'source.xlsx'
    source_file = main_sheet_path + filename

Maybe filename is set to some other file which is not present hence it is giving you error.
Try to set filename='source.xlsx'

Maybe it will help

Body:
I have a simple JSON file that I was supposed to use as a configuration file, it contains the default directories for whoever is running the script using their MacBooks:

{
  "main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
  "reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
}

I read the JSON file and obtain the values using this code:

with open('reportconfig.json','r') as j:
    config_data = json.load(j)

main_sheet_path = str(config_data.get('main_sheet_path'))
reference_sheet_path = str(config_data.get('reference_sheet_path'))

I use the path to check for a source file's existence before doing anything with it:

source_file = 'source.xlsx'
source_file = main_sheet_path + filename
if not os.path.isfile(source_file) :
    print ('ERROR: Source file \'' + source_file + '\' NOT FOUND!')
    return

Note that the filename is inputted as a parameter when the script is run (there are multiple files, the script has to know which one to target).

The file is there for sure but the script never seems to "see" it so I get that "ERROR" that I printed in the above code. Why do I think there are invisible characters? Because when I copy and paste from what was printed in the "error" notice above into the terminal, the last few characters of the file name always gets substituted by some invisible characters and hitting backspace erases characters where the cursor isn't supposed to be.

How do I know for sure that the file is there and that my problem is with reading the JSON file and not in the Directory names or anywhere else in the code? Because I finally gave up on using a JSON config file and went with a configuration file like this instead:

#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
file_paths = { "main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
               "reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
             }

I then just import the file and obtain the values like this:

import reportconfig as cfg
main_sheet_path = cfg.file_paths['main_sheet_path']
reference_sheet_path = cfg.file_paths['reference_sheet_path']
...

This workaround works perfectly — I don't get the "error" that the file isn't there when it is and the rest of the script is executed as expected. When the file isn't there, I get the proper "error" I expect and copying-and-pasting the full path and filename from the "error message" gives me the complete file name and hitting the backspace erases the right characters (no funny behavior, no invisible characters).

But could anyone please tell me how read the JSON file properly without getting those pesky invisible characters? I've spent hours trying to figure it out including searching seemingly related questions in stackoverflow but couldn't find the answer. TIA!