问:
(Android 2.1) "onContextItemSelected" and "window already focused, ignoring focus <snap irrelavant rest>"
I encounter this strange problem. I have followed the http://developer.android.com/guide/topics/ui/menus.html#context-menu exactly. I already tested it on separate dummy application and it worked fine. The problem is "Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@xxxxxx" whenever I tried to click any context menu item after pressing-and-holding any list item. "onContextItemSelected" method is never called at all time.

Here're the condensed codes:

TaskActivity.java

```<code>public class TaskActivity extends Activity{
    private ListView task_list;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);//custom xml file of my GUI

        task_list = (ListView) findViewById(R.id.listTasks);

        populateTaskList();//snapped method
        registerForContextMenu(task_list);

     }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
        menu.setHeaderTitle("Options");
        Log.v("CBC","HERE2");//It logs, yes

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Log.v("CBC","HERE1");//Not ever logged this message!
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit_menuitem:
                update_task(info.id);
                return true;
            case R.id.delete_menuitem:
                Log.v("CBC","HERE2");
                delete_task(info.id);
                return true;
        }

        return super.onContextItemSelected(item);

    }
}

<snap irrelevant codes that have played no role in this problem>
</code>```

activity_layout.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/white_bg"
    android:orientation="vertical">
    <snap irrelvant codes>
    <ListView android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/list_selectors"
        android:id="@+id/listTasks"/>
</LinearLayout>
</code>```

task_row.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@drawable/row_selector"
    android:padding="5dip">
    <TextView android:id="@+id/body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20dip"/>
    <TextView android:id="@+id/mark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20dip"/>
</LinearLayout>
</code>```

So I am wondering if you have known anything about this such strange problem? Let me know if you need to know more codes else. I assure you they are not relevant.

P.S. This is my big first application written.
P.S.S. I just write this little application for my special needs on my Android phone. (Android market free ones are unsuitable to me).

答:
this explains why you cant use onMenuItemSelectedmethod and onContextItemSelected together..

http://biginteger.blogspot.com/2010/09/solution-to-oncontextitemselected-not.html

Body:
I encounter this strange problem. I have followed the http://developer.android.com/guide/topics/ui/menus.html#context-menu exactly. I already tested it on separate dummy application and it worked fine. The problem is "Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@xxxxxx" whenever I tried to click any context menu item after pressing-and-holding any list item. "onContextItemSelected" method is never called at all time.

Here're the condensed codes:

TaskActivity.java

public class TaskActivity extends Activity{
    private ListView task_list;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);//custom xml file of my GUI

        task_list = (ListView) findViewById(R.id.listTasks);

        populateTaskList();//snapped method
        registerForContextMenu(task_list);

     }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
        menu.setHeaderTitle("Options");
        Log.v("CBC","HERE2");//It logs, yes

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Log.v("CBC","HERE1");//Not ever logged this message!
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit_menuitem:
                update_task(info.id);
                return true;
            case R.id.delete_menuitem:
                Log.v("CBC","HERE2");
                delete_task(info.id);
                return true;
        }

        return super.onContextItemSelected(item);

    }
}

<snap irrelevant codes that have played no role in this problem>

activity_layout.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/white_bg"
    android:orientation="vertical">
    <snap irrelvant codes>
    <ListView android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/list_selectors"
        android:id="@+id/listTasks"/>
</LinearLayout>

task_row.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@drawable/row_selector"
    android:padding="5dip">
    <TextView android:id="@+id/body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20dip"/>
    <TextView android:id="@+id/mark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20dip"/>
</LinearLayout>

So I am wondering if you have known anything about this such strange problem? Let me know if you need to know more codes else. I assure you they are not relevant.

P.S. This is my big first application written.
P.S.S. I just write this little application for my special needs on my Android phone. (Android market free ones are unsuitable to me).


来源: stackexchange

问:
Changing custom alert dialog's multi choice text color
How does one change the text color of the multiple selectable items in a custom alert dialog:

```<code>    <item name="android:textColorPrimary">@color/colorPrimary</item>
</code>```

That doesn't seem to be working in the styles xml, I want it to be red but its defaulting to black.

The title, positive, and negative buttons have been changed via:

```<code>    //negative button text color
    <item name="colorAccent">@color/colorAccent</item>

    //title text color
    <item name="android:textColor">@color/colorPrimary</item>
</code>```

答:
You can use:</p>
```<code><item name="textColorAlertDialogListItem">#E91E63</item>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How does one change the text color of the multiple selectable items in a custom alert dialog:

    <item name="android:textColorPrimary">@color/colorPrimary</item>

That doesn't seem to be working in the styles xml, I want it to be red but its defaulting to black.

The title, positive, and negative buttons have been changed via:

    //negative button text color
    <item name="colorAccent">@color/colorAccent</item>

    //title text color
    <item name="android:textColor">@color/colorPrimary</item>

Body:
You can use:

<item name="textColorAlertDialogListItem">#E91E63</item>

ContentLicense: CC BY-SA 4.0


问:
Py.Test add marker to all tests
I am using python asyncio with pytest-aysncio, which means all my tests look like:

```<code>@pytest.mark.asyncio
async def test_my_func():
    result = await my_func()
    assert result == expected
</code>```

Which works great, but I would prefer to not have to decorate every single function in order to get them to work. Is there a way in pytest to add this marker to every test function?

答:
If you are using pytest-asyncio>=0.17, you can put the following into your pytest.ini:

```<code>[pytest]
asyncio_mode=auto
</code>```

This removes the need to mark each test; just declaring the test function with async def is sufficient.

Title: Py.Test add marker to all tests

Body:
I am using python asyncio with pytest-aysncio, which means all my tests look like:

@pytest.mark.asyncio
async def test_my_func():
    result = await my_func()
    assert result == expected

Which works great, but I would prefer to not have to decorate every single function in order to get them to work. Is there a way in pytest to add this marker to every test function?

Body:
If you are using pytest-asyncio>=0.17, you can put the following into your pytest.ini:

[pytest]
asyncio_mode=auto

This removes the need to mark each test; just declaring the test function with async def is sufficient.


问:
How to access SQL Data of your website (phpmyadmin) from python
I am new to all this stuff

I am trying to access my website database (phpmyadmin) from python. All the tutorials available on internet are using xampp localhost which is perfectly working but When I replace localhost with my website address or host ip at it gives error ([Errno 11001] getaddrinfo failed)

```<code>import pymysql

db = pymysql.connect(host='localhost', user='root',passwd='')
cursor = db.cursor()
query = ("SHOW DATABASES")
cursor.execute(query)
for r in cursor:
    print(r)
</code>```

OUTPUT

```<code>('indus',)
('information_schema',)
('mysql',)
('performance_schema',)
('phpmyadmin',)
('test',)
('wordpress',)
</code>```

replacing localhost with website address or domain ip gives output

```<code>Traceback (most recent call last):
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 613, in connect
    sock = socket.create_connection(
  File "C:\Users\HYSTOU\AppData\Local\Programs\Python\Python39\lib\socket.py", line 823, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\HYSTOU\AppData\Local\Programs\Python\Python39\lib\socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\indusExtractingFloat.py", line 26, in <module>
    db = pymysql.connect(host='https://www.rubick.org/', user='root',passwd='')
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 353, in __init__
    self.connect()
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 664, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'https://www.rubick.org/' ([Errno 11001] getaddrinfo failed)")
</code>```

Using other methods gives (Times out)

答:
When you define the host connection, basically you say that you want to connect to a given node on the web. If the value of host is localhost, that means that your application will connect to the database of the same computer.

Yes, you can connect to a remote host as well, but it's not necessarily as easy as you would like. A problem that you definitely have is that you set the host value to https://www.rubick.org/, which is incorrect, because HTTPS is a protocol that you may use to reach a resource from your browser, but it's not part of the host's name. Try www.rubick.org instead.

Assuming that the host name is correct, you may also need to perform some further steps in order to ensure that this connection is successful, such as connecting to a VPN or any other steps necessary that your sysadmin may specify that you need to do.

Body:
I am new to all this stuff

I am trying to access my website database (phpmyadmin) from python. All the tutorials available on internet are using xampp localhost which is perfectly working but When I replace localhost with my website address or host ip at it gives error ([Errno 11001] getaddrinfo failed)

import pymysql

db = pymysql.connect(host='localhost', user='root',passwd='')
cursor = db.cursor()
query = ("SHOW DATABASES")
cursor.execute(query)
for r in cursor:
    print(r)

OUTPUT

('indus',)
('information_schema',)
('mysql',)
('performance_schema',)
('phpmyadmin',)
('test',)
('wordpress',)

replacing localhost with website address or domain ip gives output

Traceback (most recent call last):
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 613, in connect
    sock = socket.create_connection(
  File "C:\Users\HYSTOU\AppData\Local\Programs\Python\Python39\lib\socket.py", line 823, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\HYSTOU\AppData\Local\Programs\Python\Python39\lib\socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\indusExtractingFloat.py", line 26, in <module>
    db = pymysql.connect(host='https://www.rubick.org/', user='root',passwd='')
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 353, in __init__
    self.connect()
  File "C:\Users\HYSTOU\PycharmProjects\HelloWorld\venv\lib\site-packages\pymysql\connections.py", line 664, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'https://www.rubick.org/' ([Errno 11001] getaddrinfo failed)")

Using other methods gives (Times out)


问:
restructure array in php
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

```<code>Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)
</code>```

Output:

```<code>Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)
</code>```

答:
This can be accomplished by a simple foreach loop:

```<code>$start_array; // The array you want to convert
$end_array = array (); // The final array
foreach ($start_array as $index => $value) {
    if (empty($value["group_name"])) {
        $end_array[$index] = $value;
    } else {
        $end_array[$value["group_name"]][$index] = $value;
    }
}
</code>```

Title: restructure array in php

Body:
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)

Output:

Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)

Body:
This can be accomplished by a simple foreach loop:

$start_array; // The array you want to convert
$end_array = array (); // The final array
foreach ($start_array as $index => $value) {
    if (empty($value["group_name"])) {
        $end_array[$index] = $value;
    } else {
        $end_array[$value["group_name"]][$index] = $value;
    }
}


问:
Node module unzip file with password
Im looking for node package to unzip password protected zip files.
As of now i have looked here

But the above provides functions to open the files and parses the files one by one. I require to just extract the files at one place.

答:
If you want to unzip a password-protected file from a directory -

```<code>const unzipper = require("unzipper");

const unzipAndUnlockZipFile = async (filepath, password) => {
  try {
    const zipDirectory = await unzipper.Open.file(filepath); // unzip a file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password (password is optional, do not pass this if the file is not password-protected)

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zipFilePath = "./src/application.zip";
const password = "1234";
unzipAndUnlockZipFile(zipFilePath, password);
</code>```

If you want to unzip and extract the file from a buffer then the solution would look like below -

```<code>const unzipper = require("unzipper");

const unzipAndUnlockZipFileFromBuffer = async (zippedFileBase64, password) => {
  try {
    const zipBuffer = Buffer.from(zippedFileBase64, "base64"); // Change base64 to buffer
    const zipDirectory = await unzipper.Open.buffer(zipBuffer); // unzip a buffered file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password (password is optional, do not pass this if the file is not password-protected)

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zippedFileBase64 = "{{BASE64}}";
const password = "1234";
unzipAndUnlockZipFileFromBuffer(zippedFileBase64, password);
</code>```

Title: Node module unzip file with password

Body:
If you want to unzip a password-protected file from a directory -

const unzipper = require("unzipper");

const unzipAndUnlockZipFile = async (filepath, password) => {
  try {
    const zipDirectory = await unzipper.Open.file(filepath); // unzip a file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password (password is optional, do not pass this if the file is not password-protected)

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zipFilePath = "./src/application.zip";
const password = "1234";
unzipAndUnlockZipFile(zipFilePath, password);

If you want to unzip and extract the file from a buffer then the solution would look like below -

const unzipper = require("unzipper");

const unzipAndUnlockZipFileFromBuffer = async (zippedFileBase64, password) => {
  try {
    const zipBuffer = Buffer.from(zippedFileBase64, "base64"); // Change base64 to buffer
    const zipDirectory = await unzipper.Open.buffer(zipBuffer); // unzip a buffered file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password (password is optional, do not pass this if the file is not password-protected)

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zippedFileBase64 = "{{BASE64}}";
const password = "1234";
unzipAndUnlockZipFileFromBuffer(zippedFileBase64, password);


问:
Performing minus from parent to child files using powershell
I have three files in test1 folder:

I have three files in test2 folder:

Common between these two folders is file2.

I want to subtract common files between these two folders and get only unique files from test1 folder.

My expected output is:

```<code>file1.txt
file3.txt
</code>```

I tried using:

```<code>cls
$parent='D:\test1'
$child='D:\test2'
$final = [System.Collections.ArrayList]@()

$parentarrays=Get-ChildItem $parent
$childarrays=Get-ChildItem $child

foreach ($p1 in $parentarrays) {
 foreach ($p2 in $childarrays){
   if($p1 -notcontains $p2){
      $final.add($p1)
   }
 }
 }

 Write-Host $final
</code>```

But I am getting output:

```<code>file1.txt.txt file1.txt.txt file1.txt.txt file2.txt.txt file2.txt.txt file2.txt.txt file3.txt.txt file3.txt.txt file3.txt.txt
</code>```

答:
Get a list of filenames in folder 2 and do the same for folder1. Use a Where-Object clause to filter out any filename that is also in the reference list:

```<code>$filesInFolder2 = (Get-ChildItem -Path 'D:\Test2' -File).Name
(Get-ChildItem -Path 'D:\Test1' -File).Name | Where-Object { $filesInFolder2 -notcontains $_ }
</code>```

Output:

```<code>file1.txt
file3.txt
</code>```

Body:
I have three files in test1 folder:

I have three files in test2 folder:

Common between these two folders is file2.

I want to subtract common files between these two folders and get only unique files from test1 folder.

My expected output is:

file1.txt
file3.txt

I tried using:

cls
$parent='D:\test1'
$child='D:\test2'
$final = [System.Collections.ArrayList]@()

$parentarrays=Get-ChildItem $parent
$childarrays=Get-ChildItem $child

foreach ($p1 in $parentarrays) {
 foreach ($p2 in $childarrays){
   if($p1 -notcontains $p2){
      $final.add($p1)
   }
 }
 }

 Write-Host $final

But I am getting output:

file1.txt.txt file1.txt.txt file1.txt.txt file2.txt.txt file2.txt.txt file2.txt.txt file3.txt.txt file3.txt.txt file3.txt.txt

Body:
Get a list of filenames in folder 2 and do the same for folder1. Use a Where-Object clause to filter out any filename that is also in the reference list:

$filesInFolder2 = (Get-ChildItem -Path 'D:\Test2' -File).Name
(Get-ChildItem -Path 'D:\Test1' -File).Name | Where-Object { $filesInFolder2 -notcontains $_ }

Output:

file1.txt
file3.txt


问:
How to parse numbers in strings and sort them?
I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

```<code>const array = ["test 3","test 1","some test","another test","test 2"];
</code>```

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.

答:
You need to get a numerical value from the string or a large value to sort strings without any digit to the bottom. then sort by string.

const
    getDigits = s => (s.match(/\d+/) || [Number.MAX_VALUE])[0],
    array = ["test 3", "test 1", "some test", "another test", "test 2"];

array.sort((a, b) =>
    getDigits(a) - getDigits(b) ||
    a.localeCompare(b)
);

console.log(array);```

Body:
I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

const array = ["test 3","test 1","some test","another test","test 2"];

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.


答:
Something like this:</p>

```<code>$array_dst = array();
foreach ($array_src as $group_key=>$group_data){
    $group_name = $group_data['group_name'];
    if (empty($array_dst[$group_name]))
        $array_dst[$group_name] = array();
    $array_dst[$group_name][$group_key] = $group_data;
}
</code>```

Title: restructure array in php

Body:
Something like this:

$array_dst = array();
foreach ($array_src as $group_key=>$group_data){
    $group_name = $group_data['group_name'];
    if (empty($array_dst[$group_name]))
        $array_dst[$group_name] = array();
    $array_dst[$group_name][$group_key] = $group_data;
}


问:
Alert dialog styling not changing multichoice items text color
I am using a style to well, style my Alert Dialog, most of it is styled as you can see below but the multichoice items are not getting the color change. I would also like to have the checkboxes in white but am not sure how to do that.

Alert Dialog:

```<code>android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this, R.style.AlertDialogDarkBlue);

builder.setTitle("Faulty Part");

final ArrayList<Integer> selectedFaults = new ArrayList<>();

builder.setMultiChoiceItems(faultsList, null, new DialogInterface.OnMultiChoiceClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
        if (isChecked) {
            // If the user checked the item, add it to the selected items
            selectedFaults.add(indexSelected);
        } else if (selectedFaults.contains(indexSelected)) {
            // Else, if the item is already in the array, remove it
            selectedFaults.remove(Integer.valueOf(indexSelected));
        }
    }
});

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();

        onResume();
    }
});

android.app.AlertDialog alert = builder.create();

alert.show();
</code>```

AlertDialogBlue style:

```<code><style name="AlertDialogDarkBlue" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:textColor">@color/colorWhite</item>
    <item name="textColorAlertDialogListItem">@color/colorWhite</item>
    <item name="android:background">@color/colorDarkBlue</item>
</style>
</code>```

How it currently looks:

答:
You can use:</p>
```<code><item name="textColorAlertDialogListItem">@color/your_color</item>
</code>```

Body:
I am using a style to well, style my Alert Dialog, most of it is styled as you can see below but the multichoice items are not getting the color change. I would also like to have the checkboxes in white but am not sure how to do that.

Alert Dialog:

android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this, R.style.AlertDialogDarkBlue);

builder.setTitle("Faulty Part");

final ArrayList<Integer> selectedFaults = new ArrayList<>();

builder.setMultiChoiceItems(faultsList, null, new DialogInterface.OnMultiChoiceClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
        if (isChecked) {
            // If the user checked the item, add it to the selected items
            selectedFaults.add(indexSelected);
        } else if (selectedFaults.contains(indexSelected)) {
            // Else, if the item is already in the array, remove it
            selectedFaults.remove(Integer.valueOf(indexSelected));
        }
    }
});

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();

        onResume();
    }
});

android.app.AlertDialog alert = builder.create();

alert.show();

AlertDialogBlue style:

How it currently looks:

Body:
You can use:

<item name="textColorAlertDialogListItem">@color/your_color</item>


问:
Divide number into digits and save them in list (array) using python
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

```<code>dig = [0 for i in range(10)]
</code>```

and then

```<code>i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num
</code>```

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

```<code>i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1
</code>```

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

答:
Although map is often said to be unpythonic, this task is definitely for it:

```<code>>>> d = 123456
>>> map(int, str(d))
[1, 2, 3, 4, 5, 6]
</code>```

Body:
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

dig = [0 for i in range(10)]

and then

i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

Body:
Although map is often said to be unpythonic, this task is definitely for it:

>>> d = 123456
>>> map(int, str(d))
[1, 2, 3, 4, 5, 6]


问:
How do I encode categorical values in a Pandas DataFrame using a dictionary scheme given in an Excel file?
I have a Pandas DataFrame with a key attribute and other categorical attributes. How can I encode the categorical attributes using the 'dictionary' in this excel file?

This is the dataframe

and this is the excel file

I want to encode every categorical variable, say, for example, ACGB03A from the DataFrame by looking it up in the 'VARIABLE' column of the excel file, and getting the corresponding integer value from the 'Value Scheme Detail' column.

'VARIABLE' is the key, and 'Value Scheme Detail' gives the encoding details. I need to encode it from the string in the DataFrame to the corresponding integer specified in the 'Value Scheme Detail' column for the particular 'VARIABLE'.

I have around 300 columns in the dataset, so I'd like a way to encode automatically without hardcoding the strings and integers in.

Thanks.

答:
A simpler and faster solution to your problem can be to just create a dictionary from your column using split and then map it to all the required columns.
Here if your data frame is df --</p>
```<code>import pandas as pd

excel_read = pd.DataFrame(excel_file.xlsx)
# Removing rows with Value Scheme Detailed as NaN for creating dictionary
excel = excel_read[excel_read['Value Scheme Detailed'].notna()]

l = []
for s in excel['Value Scheme Detailed']:
    l.append({item.split(":")[1]:int(item.split(":")[0]) for item in s.split(";")}) #remove int if final values needed as text
d = dict(zip(excel['Variable'], l))

columns_to_map = [] # add all columns where you want to map from excel
for col in columns_to_map:
    df[col] = df[col].map(d[col])
</code>```

Body:
A simpler and faster solution to your problem can be to just create a dictionary from your column using split and then map it to all the required columns.
Here if your data frame is df --

import pandas as pd

excel_read = pd.DataFrame(excel_file.xlsx)
# Removing rows with Value Scheme Detailed as NaN for creating dictionary
excel = excel_read[excel_read['Value Scheme Detailed'].notna()]

l = []
for s in excel['Value Scheme Detailed']:
    l.append({item.split(":")[1]:int(item.split(":")[0]) for item in s.split(";")}) #remove int if final values needed as text
d = dict(zip(excel['Variable'], l))

columns_to_map = [] # add all columns where you want to map from excel
for col in columns_to_map:
    df[col] = df[col].map(d[col])


问:
How to repair OrientDB broken links from the java API?
I need to repair some broken links in my OrientDB database. Running REPAIR DATABASE --fix-links from the console works, but I would like to be able to run it from java (scala actually) code.

I tried to execute the REPAIR command as a query but it is not accepted. I also tried to "manually" repair the links by executing commands like

```<code>UPDATE Comment SET author = NULL WHERE (SELECT expand(author)) is NULL;
</code>```

or

```<code>UPDATE Comment SET author = NULL WHERE (SELECT expand($parent.$current.author)) is NULL;
</code>```

but they either trigger an error or have no effect.

How can I repair my broken links from the java API?

答:
I managed to remove the broken links by looking for a property that should be on the linked entity.</p>
```<code>UPDATE Comment SET author = NULL WHERE author.id IS NULL;
</code>```

Body:
I need to repair some broken links in my OrientDB database. Running REPAIR DATABASE --fix-links from the console works, but I would like to be able to run it from java (scala actually) code.

I tried to execute the REPAIR command as a query but it is not accepted. I also tried to "manually" repair the links by executing commands like

UPDATE Comment SET author = NULL WHERE (SELECT expand(author)) is NULL;

or

UPDATE Comment SET author = NULL WHERE (SELECT expand($parent.$current.author)) is NULL;

but they either trigger an error or have no effect.

How can I repair my broken links from the java API?

Body:
I managed to remove the broken links by looking for a property that should be on the linked entity.

UPDATE Comment SET author = NULL WHERE author.id IS NULL;


问:
How to specify username/password in Java Metro?
I'm trying to create a Web Service Client with Metro that uses WS-Security.

I have used Axis2, and to specify the username/password in an Axis2 client, I do:

```<code>org.apache.axis2.client.ServiceClient sc = stub._getServiceClient();
org.apache.axis2.client.Options options = sc.getOptions();
options.setUserName("USERNAME");
options.setPassword("PASSWORD");
</code>```

How do I provide a username/password in a Metro client?

答:
If you want to auth using basic http headers:

```<code>@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    Map<String, Object> context = ((BindingProvider)service).getRequestContext();

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("yourusername"));
    headers.put("Password", Collections.singletonList("yourpassword"));

    return service;
}
</code>```

If the service uses NTLM (Windows authentication) (explanation here):

```<code>@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
    Authenticator.setDefault(auth);

    return service;
}
</code>```

Haven't used this myself, but seen other use it:

```<code>@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    Map<String, Object> context = ((BindingProvider)service).getRequestContext();

    context.put(BindingProvider.USERNAME_PROPERTY, "yourusername");
    context.put(BindingProvider.PASSWORD_PROPERTY, "yourpassword");

    return service;
}
</code>```

Body:
I'm trying to create a Web Service Client with Metro that uses WS-Security.

I have used Axis2, and to specify the username/password in an Axis2 client, I do:

org.apache.axis2.client.ServiceClient sc = stub._getServiceClient();
org.apache.axis2.client.Options options = sc.getOptions();
options.setUserName("USERNAME");
options.setPassword("PASSWORD");

How do I provide a username/password in a Metro client?

Body:
If you want to auth using basic http headers:

@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    Map<String, Object> context = ((BindingProvider)service).getRequestContext();

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("yourusername"));
    headers.put("Password", Collections.singletonList("yourpassword"));

    return service;
}

If the service uses NTLM (Windows authentication) (explanation here):

@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
    Authenticator.setDefault(auth);

    return service;
}

Haven't used this myself, but seen other use it:

@WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    ICustomerService service =
        super.getPort(new QName("http://xmlns.example.com/services/Customer",
                "WSHttpBinding_ICustomerService"), ICustomerService.class,
                wsAddressing);

    Map<String, Object> context = ((BindingProvider)service).getRequestContext();

    context.put(BindingProvider.USERNAME_PROPERTY, "yourusername");
    context.put(BindingProvider.PASSWORD_PROPERTY, "yourpassword");

    return service;
}


问:
Passing get parameters to url
```<code><li v-for='category in categoriesData' :key='category.seoName'>
    <label class='custom-checkbox'>
        <input type='checkbox' :value='category.id' v-model='checkedCategories' @click='request()'>
        <span>{{ category.title }}</span>
    </label>
</li>
</code>```

There is a component with checkboxes, when clicked, it calls a function that sends an axios request. How can I add get parameters to the url without reloading the page?

答:
To resolve this issue you can use fullPath like mentioned below in request() method.

```<code>this.$router.push({path: this.$route.fullPath, query: {param: 'paramvalue} });
</code>```

Title: Passing get parameters to url

Body:
        <input type='checkbox' :value='category.id' v-model='checkedCategories' @click='request()'>
        {{ category.title }}

There is a component with checkboxes, when clicked, it calls a function that sends an axios request. How can I add get parameters to the url without reloading the page?

Body:
To resolve this issue you can use fullPath like mentioned below in request() method.

this.$router.push({path: this.$route.fullPath, query: {param: 'paramvalue} });


问:
Calculating gain or loss in a partition SQL
With SQL partitions min and max values are easy to find, but how is Gain or Loss determined over a partition?

This brings in the time element to compare min and max. If max occurs later in time than min, that would be a "Gain".  If min occurs later, that would be a "Loss".

How might the GainorLoss column be calculated?

```<code>CREATE TABLE Weights (id int, date date, person varchar(40), Weight int);

INSERT INTO Weights VALUES (1, '2022-09-01', 'Alice', 100);
INSERT INTO Weights VALUES (2, '2022-10-01', 'Alice', 105);
INSERT INTO Weights VALUES (3, '2022-11-01', 'Alice', 110);
INSERT INTO Weights VALUES (4, '2022-12-01', 'Alice', 115);
INSERT INTO Weights VALUES (5, '2022-09-01', 'Peter', 150);
INSERT INTO Weights VALUES (6, '2022-10-01', 'Peter', 145);
INSERT INTO Weights VALUES (7, '2022-11-01', 'Peter', 140);
INSERT INTO Weights VALUES (8, '2022-12-01', 'Peter', 135);

select
 person
 , date
 , weight
 , min(Weight) OVER (PARTITION BY person) as minWeight
 , max(Weight) OVER (PARTITION BY person) as maxWeight
 --if max weight occurs after min weight, then "Gain" ELSE "Loss" AS GainorLoss
 from weights
</code>```

Desired output:

person
date
weight
minWeight
maxWeight
GainorLoss

Alice
2022-09-01
100
100
120
Gain

Alice
2022-10-01
105
100
120
Gain

Alice
2022-11-01
110
100
120
Gain

Alice
2022-12-01
120
100
120
Gain

Peter
2022-09-01
150
135
150
Loss

Peter
2022-10-01
145
135
150
Loss

Peter
2022-11-01
140
135
150
Loss

Peter
2022-12-01
135
135
150
Loss

答:
You can use FIRST_VALUE to get the first or the last value based on an order.

The example below calculates 2 GainOrLess results.

The 2nd is what you described. The 1st is what I think you want.

But with the current sample data they give same result.

```<code>select *
, CASE
  WHEN LastWeight > FirstWeight THEN 'Gain'
  WHEN LastWeight < FirstWeight THEN 'Loss'
  ELSE 'Same'
  END AS [GainOrLoss1]
, CASE
  WHEN MaxWeightDate > MinWeightDate THEN 'Gain'
  WHEN MaxWeightDate < MinWeightDate THEN 'Loss'
  ELSE 'Same'
  END AS [GainOrLoss2]
from
(
select
 person
 , [date]
 , weight
 , FIRST_VALUE(Weight) OVER (PARTITION BY person ORDER BY [date], id) as FirstWeight
 , FIRST_VALUE(Weight) OVER (PARTITION BY person ORDER BY [date] DESC, id DESC) as LastWeight
 , FIRST_VALUE([date]) OVER (PARTITION BY person ORDER BY Weight, id) as MinWeightDate
 , FIRST_VALUE([date]) OVER (PARTITION BY person ORDER BY Weight DESC, id DESC) as MaxWeightDate
 from weights
) q
ORDER BY person, [date]
</code>```

```
person | date       | weight | FirstWeight | LastWeight | MinWeightDate | MaxWeightDate | GainOrLoss1 | GainOrLoss2
:----- | :--------- | -----: | ----------: | ---------: | :------------ | :------------ | :---------- | :----------
Alice  | 2022-09-01 |    100 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-10-01 |    105 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-11-01 |    110 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-12-01 |    115 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Peter  | 2022-09-01 |    150 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-10-01 |    145 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-11-01 |    140 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-12-01 |    135 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
```

db<>fiddle here

Body:
With SQL partitions min and max values are easy to find, but how is Gain or Loss determined over a partition?

This brings in the time element to compare min and max. If max occurs later in time than min, that would be a "Gain".  If min occurs later, that would be a "Loss".

How might the GainorLoss column be calculated?

CREATE TABLE Weights (id int, date date, person varchar(40), Weight int);

INSERT INTO Weights VALUES (1, '2022-09-01', 'Alice', 100);
INSERT INTO Weights VALUES (2, '2022-10-01', 'Alice', 105);
INSERT INTO Weights VALUES (3, '2022-11-01', 'Alice', 110);
INSERT INTO Weights VALUES (4, '2022-12-01', 'Alice', 115);
INSERT INTO Weights VALUES (5, '2022-09-01', 'Peter', 150);
INSERT INTO Weights VALUES (6, '2022-10-01', 'Peter', 145);
INSERT INTO Weights VALUES (7, '2022-11-01', 'Peter', 140);
INSERT INTO Weights VALUES (8, '2022-12-01', 'Peter', 135);

select
 person
 , date
 , weight
 , min(Weight) OVER (PARTITION BY person) as minWeight
 , max(Weight) OVER (PARTITION BY person) as maxWeight
 --if max weight occurs after min weight, then "Gain" ELSE "Loss" AS GainorLoss
 from weights

Desired output:

person
date
weight
minWeight
maxWeight
GainorLoss

Alice
2022-09-01
100
100
120
Gain

Alice
2022-10-01
105
100
120
Gain

Alice
2022-11-01
110
100
120
Gain

Alice
2022-12-01
120
100
120
Gain

Peter
2022-09-01
150
135
150
Loss

Peter
2022-10-01
145
135
150
Loss

Peter
2022-11-01
140
135
150
Loss

Peter
2022-12-01
135
135
150
Loss

Body:
You can use FIRST_VALUE to get the first or the last value based on an order.

The example below calculates 2 GainOrLess results.

The 2nd is what you described. The 1st is what I think you want.

But with the current sample data they give same result.

select *
, CASE
  WHEN LastWeight > FirstWeight THEN 'Gain'
  WHEN LastWeight < FirstWeight THEN 'Loss'
  ELSE 'Same'
  END AS [GainOrLoss1]
, CASE
  WHEN MaxWeightDate > MinWeightDate THEN 'Gain'
  WHEN MaxWeightDate < MinWeightDate THEN 'Loss'
  ELSE 'Same'
  END AS [GainOrLoss2]
from
(
select
 person
 , [date]
 , weight
 , FIRST_VALUE(Weight) OVER (PARTITION BY person ORDER BY [date], id) as FirstWeight
 , FIRST_VALUE(Weight) OVER (PARTITION BY person ORDER BY [date] DESC, id DESC) as LastWeight
 , FIRST_VALUE([date]) OVER (PARTITION BY person ORDER BY Weight, id) as MinWeightDate
 , FIRST_VALUE([date]) OVER (PARTITION BY person ORDER BY Weight DESC, id DESC) as MaxWeightDate
 from weights
) q
ORDER BY person, [date]

person | date       | weight | FirstWeight | LastWeight | MinWeightDate | MaxWeightDate | GainOrLoss1 | GainOrLoss2
:----- | :--------- | -----: | ----------: | ---------: | :------------ | :------------ | :---------- | :----------
Alice  | 2022-09-01 |    100 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-10-01 |    105 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-11-01 |    110 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Alice  | 2022-12-01 |    115 |         100 |        115 | 2022-09-01    | 2022-12-01    | Gain        | Gain
Peter  | 2022-09-01 |    150 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-10-01 |    145 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-11-01 |    140 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss
Peter  | 2022-12-01 |    135 |         150 |        135 | 2022-12-01    | 2022-09-01    | Loss        | Loss

db<>fiddle here


问:
How to prevent EventStore access error on first run
My Mac application accessing the user calendar shows a permission access error on the first run before asking the user for Calendar access permission. The message does not appear on later runs. How can I prevent it? I use the following code:

```<code>class MyCalendar {
   let store = EKEventStore()
   init() {
      func requestAccessToCalendar() {
          store.requestAccess(to: .event, completion:
            {(granted: Bool, error: Error?) -> Void in
          })
      }
      func loadCalendars() {
          calendars = store.calendars(for: .event)
      }

      let ekstatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
      switch (ekstatus) {
         case EKAuthorizationStatus.notDetermined:
            requestAccessToCalendar()
         case EKAuthorizationStatus.authorized:
            loadCalendars()
         case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
            dialogOK("access to Calendar denied")
         @unknown default:
            dialogOK("Unknown Calendar access problem")
         }
   }
}
</code>```

The error occurs before any statement in the init() is executed. I also tried with a lazy var instead of a constant for store - without success. The plist entitlement is properly set an the application works as expected beside this error messages.

What is my mistake?

答:
I struggled with this for a while as well. As hinted elsewhere, you likely need to add the reason to the Info.plist, e.g.:</p>
```<code><dict>
    <key>NSCalendarsUsageDescription</key>
    <string>Export event information</string>
</dict>
</code>```

Body:
My Mac application accessing the user calendar shows a permission access error on the first run before asking the user for Calendar access permission. The message does not appear on later runs. How can I prevent it? I use the following code:

class MyCalendar {
   let store = EKEventStore()
   init() {
      func requestAccessToCalendar() {
          store.requestAccess(to: .event, completion:
            {(granted: Bool, error: Error?) -> Void in
          })
      }
      func loadCalendars() {
          calendars = store.calendars(for: .event)
      }

      let ekstatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
      switch (ekstatus) {
         case EKAuthorizationStatus.notDetermined:
            requestAccessToCalendar()
         case EKAuthorizationStatus.authorized:
            loadCalendars()
         case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
            dialogOK("access to Calendar denied")
         @unknown default:
            dialogOK("Unknown Calendar access problem")
         }
   }
}

The error occurs before any statement in the init() is executed. I also tried with a lazy var instead of a constant for store - without success. The plist entitlement is properly set an the application works as expected beside this error messages.

What is my mistake?

Body:
I struggled with this for a while as well. As hinted elsewhere, you likely need to add the reason to the Info.plist, e.g.:

<dict>
    <key>NSCalendarsUsageDescription</key>
    <string>Export event information</string>
</dict>


问:
Unzip a password-protected archive using node-js
I need to read a content of a password-protected archive (zip is preferred) to a node-js app, without writing the protected content to a file

In addition, the app is cross-platform so solution such this doesn't help

I looked also here but there is no code in the answer

答:
This solution will read the file buffer which you can get from base64 or by reading the zip file, after that unzipping and opening the password-protected file is done in-memory. I hope this helps -</p>
```<code>const unzipper = require("unzipper");

const unzipAndUnlockZipFileFromBuffer = async (zippedFileBase64, password) => {
  try {
    const zipBuffer = Buffer.from(zippedFileBase64, "base64"); // Change base64 to buffer
    const zipDirectory = await unzipper.Open.buffer(zipBuffer); // unzip a buffered file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zippedFileBase64 = "{{BASE64}}";
const password = "1234";
unzipAndUnlockZipFileFromBuffer(zippedFileBase64, password);
</code>```

Body:
This solution will read the file buffer which you can get from base64 or by reading the zip file, after that unzipping and opening the password-protected file is done in-memory. I hope this helps -

const unzipper = require("unzipper");

const unzipAndUnlockZipFileFromBuffer = async (zippedFileBase64, password) => {
  try {
    const zipBuffer = Buffer.from(zippedFileBase64, "base64"); // Change base64 to buffer
    const zipDirectory = await unzipper.Open.buffer(zipBuffer); // unzip a buffered file
    const file = zipDirectory.files[0]; // find the file you want

    // if you want to find a specific file by path
    // const file = zipDirectory.files.find((f) => f.path === "filename");

    const extracted = await file.buffer(password); // unlock the file with the password

    console.log(extracted.toString()); // file content
  } catch (e) {
    console.log(e);
  }
};

const zippedFileBase64 = "{{BASE64}}";
const password = "1234";
unzipAndUnlockZipFileFromBuffer(zippedFileBase64, password);


问:
intervation image wont store image in public path after i uploaded my laravel project on host
i have a project that it has some posts on it
i have made admin panel to create new posts
since i uploaded my project on cpanel host i can create a post but image wont shown in my post but before that on my localhost i can craete a post and store image in my path
i checked my public path in my host and saw that there isn,t any new image related to my post that i have created with my admin panel on my host just my image name has saved in my database

this is my blog blade file

```<code><section class="w-80 mx-auto my-5">
    <div class="container">
        <div class="row">
            @foreach($posts as $post)
                <div class="col-md-4 translate-box relative mb-4">
                    <div class="blog-box-height">
                        <a href="{{route('blog.single',['title'=>$post->title])}}"> <img src="{{asset('image/'.$post->header_image)}}" alt="{{$post->title}}" class="img-fluid"></a>
                        <div class="py-3 px-4">
                            <a class="text-xmedium fw-bold text-decoration-none text-black" href="{{route('blog.single',['title'=>$post->title])}}">
                                {{str_replace('_',' ',$post->title)}}
                            </a>
                            <p class="text-muted-1 mt-2 text-small">
                               {!! strip_tags(mb_substr($post->content,0,270,'utf-8')) !!} ...
                            </p>
                            <div class="box-time absolute">
                                <p class="text-muted-1"><i class="far fa-clock"></i> {{$post->time}} دقیقه</p>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    </div>
</section>
</code>```

this is my postcontroller codes

```<code>public function storeImage(Request $request)
{
    $image_name = null;
    if ($request->file('image')) {
        $image = $request->file('image')->getClientOriginalName();
        $image_name = time() . $image;
        $folder = public_path('/image');
        $path = $folder . '/' . $image_name;

        if (is_dir($folder)) {
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        } else {
            File::makeDirectory($folder, 0755, true);
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        }
    }

    return $image_name;
}
</code>```

this code works great in my localhost server but when i uploaded it on host i think image intervation wont work

答:
Try with 777 permission for make directory.

File::makeDirectory($folder, 0777, true);

Body:
i have a project that it has some posts on it
i have made admin panel to create new posts
since i uploaded my project on cpanel host i can create a post but image wont shown in my post but before that on my localhost i can craete a post and store image in my path
i checked my public path in my host and saw that there isn,t any new image related to my post that i have created with my admin panel on my host just my image name has saved in my database

this is my blog blade file

            @foreach($posts as $post)

                        $post->title])}}"> header_image)}}" alt="{{$post->title}}" class="img-fluid">

                            $post->title])}}">
                                {{str_replace('_',' ',$post->title)}}

                               {!! strip_tags(mb_substr($post->content,0,270,'utf-8')) !!} ...

 {{$post->time}} دقیقه

            @endforeach

this is my postcontroller codes

public function storeImage(Request $request)
{
    $image_name = null;
    if ($request->file('image')) {
        $image = $request->file('image')->getClientOriginalName();
        $image_name = time() . $image;
        $folder = public_path('/image');
        $path = $folder . '/' . $image_name;

        if (is_dir($folder)) {
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        } else {
            File::makeDirectory($folder, 0755, true);
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        }
    }

    return $image_name;
}

this code works great in my localhost server but when i uploaded it on host i think image intervation wont work


问:
How to run a java class only once in background, in a feature file
I have a statement in the background of a feature file as,

```<code>def token = Java.type("Calling a static method from a java class")
</code>```

I have 4 scenarios in my feature file and this java class is called 4 times. How to call this java class only once?

Body:
I have a statement in the background of a feature file as,

def token = Java.type("Calling a static method from a java class")

I have 4 scenarios in my feature file and this java class is called 4 times. How to call this java class only once?

Body:
Background:

karate.callSingle('called.feature@scenarioToBeCalledOnceInBackground');


问:
c# splitting and retrieving values from a string
I have a string like this:

```<code>"http://localhost:55164/Images/photos/2/2.jpg"
</code>```

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

答:
One quick way you could do with would be to split the string by the forward slash.

In this way you'll know that the last item in the array and the second-to-last item will be what you require.

Such that:

```<code>string url = "http://localhost:55164/Images/photos/2/2.jpg";
string[] urlParts = url.Split('/');
string file = urlParts[urlParts.length -1];
</code>```

Body:
I have a string like this:

"http://localhost:55164/Images/photos/2/2.jpg"

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

Body:
One quick way you could do with would be to split the string by the forward slash.

In this way you'll know that the last item in the array and the second-to-last item will be what you require.

Such that:

string url = "http://localhost:55164/Images/photos/2/2.jpg";
string[] urlParts = url.Split('/');
string file = urlParts[urlParts.length -1];


问:
How to add fonts to create-react-app based projects?
I'm using create-react-app and prefer not to eject.

It's not clear where fonts imported via @font-face and loaded locally should go.

Namely, I'm loading

```<code>@font-face {
  font-family: 'Myriad Pro Regular';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Regular'), url('MYRIADPRO-REGULAR.woff') format('woff');
}
</code>```

Any suggestions?

-- EDIT

Including the gist to which Dan referring in his answer

```<code>➜  Client git:(feature/trivia-game-ui-2) ✗ ls -l public/static/fonts
total 1168
-rwxr-xr-x@ 1 maximveksler  staff  62676 Mar 17  2014 MYRIADPRO-BOLD.woff
-rwxr-xr-x@ 1 maximveksler  staff  61500 Mar 17  2014 MYRIADPRO-BOLDCOND.woff
-rwxr-xr-x@ 1 maximveksler  staff  66024 Mar 17  2014 MYRIADPRO-BOLDCONDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  66108 Mar 17  2014 MYRIADPRO-BOLDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  60044 Mar 17  2014 MYRIADPRO-COND.woff
-rwxr-xr-x@ 1 maximveksler  staff  64656 Mar 17  2014 MYRIADPRO-CONDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  61848 Mar 17  2014 MYRIADPRO-REGULAR.woff
-rwxr-xr-x@ 1 maximveksler  staff  62448 Mar 17  2014 MYRIADPRO-SEMIBOLD.woff
-rwxr-xr-x@ 1 maximveksler  staff  66232 Mar 17  2014 MYRIADPRO-SEMIBOLDIT.woff
➜  Client git:(feature/trivia-game-ui-2) ✗ cat src/containers/GameModule.css
.GameModule {
  padding: 15px;
}

@font-face {
  font-family: 'Myriad Pro Regular';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Regular'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-REGULAR.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Condensed';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-COND.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Semibold Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Semibold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Semibold';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Semibold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLD.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Condensed Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-CONDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Condensed Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCONDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Condensed';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCOND.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLD.woff') format('woff');
}
</code>```

答:
This is for people using an NX(nwrl) monorepo, I have tested this while using it there, may work for other CRA apps.
First add the fonts in the assets/fonts folder, create a fonts folder, if not present.

Then in your main app.js/tsx
Add this code, with your existing jsx code

```<code><style type="text/css">{`
    @font-face {
      font-family: 'MaterialIcons';
      src: url(${require('react-native-vector-icons/Fonts/MaterialIcons.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'MaterialCommunityIcons';
      src: url(${require('react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'Mulish-Bold';
      src: url(${require('../assets/fonts/Mulish-Bold.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'Your Font Name';
      src: url(${require('../assets/fonts/font-file-name.otf')}) format('truetype');
    }
  `}</style>
</code>```

It should look something like this, wrap with Fragment tags -

```<code> <>
<style type="text/css">{`
        @font-face {
          font-family: 'MaterialIcons';
          src: url(${require('react-native-vector-icons/Fonts/MaterialIcons.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'MaterialCommunityIcons';
          src: url(${require('react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'Mulish-Bold';
          src: url(${require('../assets/fonts/Mulish-Bold.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'CircularStd-Book';
          src: url(${require('../assets/fonts/CircularStd-Book.otf')}) format('truetype');
        }
      `}</style>
   //Your JSX, or your main app level code
 </>
</code>```

There's another step, in your custom webpack config file, add these loaders, if you don't have one then, on your parent level, create a webpack.js file -

Your webpack js should look something like this -

```<code>const getWebpackConfig = require('@nrwl/react/plugins/webpack');

function getCustomWebpackConfig(webpackConfig) {
  const config = getWebpackConfig(webpackConfig);
  const isProduction = webpackConfig.mode === 'production';

  if (!isProduction) {
    config.resolve.alias = {
      'react-native': 'react-native-web',
      'react-native-linear-gradient': 'react-native-web-linear-gradient',
      'react-native-localization': 'react-localization'
    };

    config.module.rules.push(
      {
        test: /\.ttf$/,
        loader: require.resolve('file-loader'),
        options: { esModule: false, name: 'static/media/[path][name].[ext]' },
      },
      {
        test: /\.otf$/,
        loader: require.resolve('file-loader'),
        options: { esModule: false, name: 'static/media/[path][name].[ext]' },
      },
      {
        test: /\.(js|jsx)$/,
        exclude: function (content) {
          return (
            /node_modules/.test(content) &&
            !/\/react-native-paper\//.test(content) &&
            !/\/react-native-vector-icons\//.test(content) &&

          );
        },
        use: {
          loader: require.resolve('@nrwl/web/src/utils/web-babel-loader.js'),
          options: {
            presets: [
              [
                '@nrwl/react/babel',
                {
                  runtime: 'automatic',
                  useBuiltIns: 'usage',
                },
              ],
            ],
            plugins: [
                ["module-resolver", {
                    "alias": {
                      "^react-native$": "react-native-web",
                      "react-native-linear-gradient": "react-native-web-linear-gradient",
                      "react-native-localization": "react-localization"
                    }
                  }]
            ],
          },
        },
      },

    );
  }

  return config;
}

module.exports = getCustomWebpackConfig;
</code>```

Your babel loader, may be different but the ttf and otf rules are important to be added. I'm using this with react native for web functionality. You could remove the aliases if it isn't required by your project.

Thanks to this blog, which made me understand this concept better - https://blog.nrwl.io/step-by-step-guide-on-creating-a-monorepo-for-react-native-apps-using-nx-704753b6c70e

Body:
I'm using create-react-app and prefer not to eject.

It's not clear where fonts imported via @font-face and loaded locally should go.

Namely, I'm loading

@font-face {
  font-family: 'Myriad Pro Regular';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Regular'), url('MYRIADPRO-REGULAR.woff') format('woff');
}

Any suggestions?

-- EDIT

Including the gist to which Dan referring in his answer

➜  Client git:(feature/trivia-game-ui-2) ✗ ls -l public/static/fonts
total 1168
-rwxr-xr-x@ 1 maximveksler  staff  62676 Mar 17  2014 MYRIADPRO-BOLD.woff
-rwxr-xr-x@ 1 maximveksler  staff  61500 Mar 17  2014 MYRIADPRO-BOLDCOND.woff
-rwxr-xr-x@ 1 maximveksler  staff  66024 Mar 17  2014 MYRIADPRO-BOLDCONDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  66108 Mar 17  2014 MYRIADPRO-BOLDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  60044 Mar 17  2014 MYRIADPRO-COND.woff
-rwxr-xr-x@ 1 maximveksler  staff  64656 Mar 17  2014 MYRIADPRO-CONDIT.woff
-rwxr-xr-x@ 1 maximveksler  staff  61848 Mar 17  2014 MYRIADPRO-REGULAR.woff
-rwxr-xr-x@ 1 maximveksler  staff  62448 Mar 17  2014 MYRIADPRO-SEMIBOLD.woff
-rwxr-xr-x@ 1 maximveksler  staff  66232 Mar 17  2014 MYRIADPRO-SEMIBOLDIT.woff
➜  Client git:(feature/trivia-game-ui-2) ✗ cat src/containers/GameModule.css
.GameModule {
  padding: 15px;
}

@font-face {
  font-family: 'Myriad Pro Regular';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Regular'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-REGULAR.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Condensed';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-COND.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Semibold Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Semibold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Semibold';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Semibold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLD.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Condensed Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-CONDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Condensed Italic';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCONDIT.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold Condensed';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCOND.woff') format('woff');
}

@font-face {
  font-family: 'Myriad Pro Bold';
  font-style: normal;
  font-weight: normal;
  src: local('Myriad Pro Bold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLD.woff') format('woff');
}

Body:
This is for people using an NX(nwrl) monorepo, I have tested this while using it there, may work for other CRA apps.
First add the fonts in the assets/fonts folder, create a fonts folder, if not present.

Then in your main app.js/tsx
Add this code, with your existing jsx code

<style type="text/css">{`
    @font-face {
      font-family: 'MaterialIcons';
      src: url(${require('react-native-vector-icons/Fonts/MaterialIcons.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'MaterialCommunityIcons';
      src: url(${require('react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'Mulish-Bold';
      src: url(${require('../assets/fonts/Mulish-Bold.ttf')}) format('truetype');
    }
    @font-face {
      font-family: 'Your Font Name';
      src: url(${require('../assets/fonts/font-file-name.otf')}) format('truetype');
    }
  `}</style>

It should look something like this, wrap with Fragment tags -

 <>
<style type="text/css">{`
        @font-face {
          font-family: 'MaterialIcons';
          src: url(${require('react-native-vector-icons/Fonts/MaterialIcons.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'MaterialCommunityIcons';
          src: url(${require('react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'Mulish-Bold';
          src: url(${require('../assets/fonts/Mulish-Bold.ttf')}) format('truetype');
        }
        @font-face {
          font-family: 'CircularStd-Book';
          src: url(${require('../assets/fonts/CircularStd-Book.otf')}) format('truetype');
        }
      `}</style>
   //Your JSX, or your main app level code
 </>

There's another step, in your custom webpack config file, add these loaders, if you don't have one then, on your parent level, create a webpack.js file -

Your webpack js should look something like this -

const getWebpackConfig = require('@nrwl/react/plugins/webpack');

function getCustomWebpackConfig(webpackConfig) {
  const config = getWebpackConfig(webpackConfig);
  const isProduction = webpackConfig.mode === 'production';

  if (!isProduction) {
    config.resolve.alias = {
      'react-native': 'react-native-web',
      'react-native-linear-gradient': 'react-native-web-linear-gradient',
      'react-native-localization': 'react-localization'
    };

    config.module.rules.push(
      {
        test: /\.ttf$/,
        loader: require.resolve('file-loader'),
        options: { esModule: false, name: 'static/media/[path][name].[ext]' },
      },
      {
        test: /\.otf$/,
        loader: require.resolve('file-loader'),
        options: { esModule: false, name: 'static/media/[path][name].[ext]' },
      },
      {
        test: /\.(js|jsx)$/,
        exclude: function (content) {
          return (
            /node_modules/.test(content) &&
            !/\/react-native-paper\//.test(content) &&
            !/\/react-native-vector-icons\//.test(content) &&

          );
        },
        use: {
          loader: require.resolve('@nrwl/web/src/utils/web-babel-loader.js'),
          options: {
            presets: [
              [
                '@nrwl/react/babel',
                {
                  runtime: 'automatic',
                  useBuiltIns: 'usage',
                },
              ],
            ],
            plugins: [
                ["module-resolver", {
                    "alias": {
                      "^react-native$": "react-native-web",
                      "react-native-linear-gradient": "react-native-web-linear-gradient",
                      "react-native-localization": "react-localization"
                    }
                  }]
            ],
          },
        },
      },

    );
  }

  return config;
}

module.exports = getCustomWebpackConfig;

Your babel loader, may be different but the ttf and otf rules are important to be added. I'm using this with react native for web functionality. You could remove the aliases if it isn't required by your project.

Thanks to this blog, which made me understand this concept better - https://blog.nrwl.io/step-by-step-guide-on-creating-a-monorepo-for-react-native-apps-using-nx-704753b6c70e


问:
The named parameter isn't defined (data persistence)
There is my error , I want to solve this problem
enter image description here
The named parameter 'itemCount' isn't defined.
The named parameter 'itemBuilder' isn't defined.</p>

答:
Hello Syed i might thing that your try to use Listview() on Place of Listview.builder()....</p>
```<code>      ListView(
        children: [
          Container(),
        ],
      ),

      ListView.builder(
          itemCount: 2,
          itemBuilder: (context, index){
            return Container();
          }
      ),
</code>```

Body:
Hello Syed i might thing that your try to use Listview() on Place of Listview.builder()....

      ListView(
        children: [
          Container(),
        ],
      ),

      ListView.builder(
          itemCount: 2,
          itemBuilder: (context, index){
            return Container();
          }
      ),


问:
Border animation on hover with a transparent section moving left to right
I have this code trying to make an animation on hover. Something like this :

```<code>TextLink      hover: TextLink
--------             --  ----
</code>```

I am trying to have an animation that looks like the "transparent" portion is moving from left till the end of the text.

body {
  margin: 0;
  background: #16263d;
}

div {
  padding: 30px;
}

a {
  color: #fff;
  text-decoration: none;
  display: block;
  margin-top: 24px;
  transition: all 0.75s ease-in-out;
}

a span {
  border-bottom: 2px solid #fff;
}

a:hover:after {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  transform: translateX(100%);
}

a:after {
  content: '';
  width: 35px;
  height: 2px;
  background: #16263d;
  display: block;
  position: relative;
  opacity: 1;
  transform: translateX(-35px);
  transition: all 0.75s ease-in-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Text Link and something more than this</span>
</div></code>```

The problem is that 100% of the transform transition is not taken into consideration ... seems like only 100px are.

答:
Try to use gradients:

span {
 --g:40px; /* the gap */

 font-size:40px;
 background:
   linear-gradient(90deg,
      black   calc(50% - var(--g)/2),
      #0000 0 calc(50% + var(--g)/2),
      black 0
   ) right bottom/calc(200% + var(--g)) 3px /* 3px = thickness */
   no-repeat;
}

span:hover {
  background-position: left bottom;
  transition:0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Some text</span></code>```

Body:
I have this code trying to make an animation on hover. Something like this :

TextLink      hover: TextLink
--------             --  ----

I am trying to have an animation that looks like the "transparent" portion is moving from left till the end of the text.

body {
  margin: 0;
  background: #16263d;
}

div {
  padding: 30px;
}

a {
  color: #fff;
  text-decoration: none;
  display: block;
  margin-top: 24px;
  transition: all 0.75s ease-in-out;
}

a span {
  border-bottom: 2px solid #fff;
}

a:hover:after {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  transform: translateX(100%);
}

a:after {
  content: '';
  width: 35px;
  height: 2px;
  background: #16263d;
  display: block;
  position: relative;
  opacity: 1;
  transform: translateX(-35px);
  transition: all 0.75s ease-in-out;
}

  Text Link and something more than this

The problem is that 100% of the transform transition is not taken into consideration ... seems like only 100px are.

Body:
Try to use gradients:

span {
 --g:40px; /* the gap */

 font-size:40px;
 background:
   linear-gradient(90deg,
      black   calc(50% - var(--g)/2),
      #0000 0 calc(50% + var(--g)/2),
      black 0
   ) right bottom/calc(200% + var(--g)) 3px /* 3px = thickness */
   no-repeat;
}

span:hover {
  background-position: left bottom;
  transition:0.5s;
}

<span>Some text</span>


问:
Some beginner Objective-C/iPhone questions
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

```
- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}
```

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

```str = [[NSString alloc] initWithString:@"Hi there!"];```

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

答:
calling

```<code>self = [super init];
</code>```

May return nil if the superclass cannot initialize itself for some reason or other, including memory being unavailable, or certain prerequisites have not been met.  If that is the case, you don't want to be trying to set variables of self, or set self as a delegate, or add self to an array, if self is nil.

The autorelease pool is something created upon every event the iPhone sends your application.  It is created before any code runs, and released after all your code is done, for each event.  Any objects that you call autorelease on will be put into the current autorelease pool.  Any objects in the autorelease pool will be released as many times as they were added, after your code completes.  In this way, you don't have to worry about who's responsible for releasing an object created by one method and returned to another method.

You can create your own autorelease pools as necessary.

```<code>str = [[NSString alloc] initWithString:@"Hi there!"];
</code>```

This line creates a string that is not in an autorelease pool, so you have to release it manually.  Simply writing

```<code>@"Hi there!";
</code>```

returns a string that you don't have to worry about releasing.  Extending your previous example:

```<code>str = [[[NSString alloc] initWithString:@"Hi there!"] autorelease];
</code>```

would be another method of creating a string you don't need to worry about releasing.

One difference between garbage collection and autorelease pools is that garbage collection works with circular references.  Using autorelease pools, you don't want to have two objects that retain each other and hope that once nothing else refers to them, they will go out of existence; they won't.

OwnerDisplayName: Karolis

ContentLicense: CC BY-SA 2.5

Body:
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

str = [[NSString alloc] initWithString:@"Hi there!"];

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

Body:
calling

self = [super init];

May return nil if the superclass cannot initialize itself for some reason or other, including memory being unavailable, or certain prerequisites have not been met.  If that is the case, you don't want to be trying to set variables of self, or set self as a delegate, or add self to an array, if self is nil.

The autorelease pool is something created upon every event the iPhone sends your application.  It is created before any code runs, and released after all your code is done, for each event.  Any objects that you call autorelease on will be put into the current autorelease pool.  Any objects in the autorelease pool will be released as many times as they were added, after your code completes.  In this way, you don't have to worry about who's responsible for releasing an object created by one method and returned to another method.

You can create your own autorelease pools as necessary.

str = [[NSString alloc] initWithString:@"Hi there!"];

This line creates a string that is not in an autorelease pool, so you have to release it manually.  Simply writing

@"Hi there!";

returns a string that you don't have to worry about releasing.  Extending your previous example:

str = [[[NSString alloc] initWithString:@"Hi there!"] autorelease];

would be another method of creating a string you don't need to worry about releasing.

One difference between garbage collection and autorelease pools is that garbage collection works with circular references.  Using autorelease pools, you don't want to have two objects that retain each other and hope that once nothing else refers to them, they will go out of existence; they won't.

OwnerDisplayName: Ed Marty


问:
C vs C++ - cross-platform
I have a very quick question to which I havn't found an answer for.
Are there any major platforms (Windows, MacOS, unix, linux, Android, iOS, etc....) out there that supports C but not C++?

Thanks

答: simply put no, the question is how you program, if a compiler is available for the platform and if your libraries are available for the target platform.</p>

Title: C vs C++ - cross-platform


问:
Dynamic View of a SQL Table in php
my task at he moment is to show the data from a sql db in a browser.
My code is fine for that, but now i have more and bigger sql tables and i am looking for a way to read and show it more dynamic. So that i dont have to write all the names of the column (the echo statements, if i have 100 columns it would not really work like this) in the code. Is there ab better way in this case?

Thanks.

```<code><?php
            error_reporting(E_ALL);

            $db_link = mysqli_connect (MYSQL_HOST,
                           MYSQL_BENUTZER,
                           MYSQL_KENNWORT,
                           MYSQL_DATENBANK);

            if ( $db_link )
            {
                echo('<p> Verbindung vorhanden: </p>');
            }
            else
            {
                    echo('<p style="color:red"> Keine Verbindung vorhanden: </p>');
            }

            $db_res = mysqli_query($db_link, "SELECT AA, B1, C3 FROM tableXYZ")
            or die("Fehler: " . mysqli_error());

            echo("<table>");
            while($row = mysqli_fetch_array($db_res))
            {
                echo("<tr>");
                echo("<td>" . $row["AA"] . "</td>");
                echo("<td>" . $row["B1"] . "</td>");
                echo("<td>" . $row["C3"] . "</td>");
                echo("</tr>");
            }
            echo("</table>");

            ?>
</code>```

答:
You could use a foreach loop to show all columns. Like this:

```<code>        while($row = mysqli_fetch_array($db_res))
        {
            echo("<tr>");
            foreach ($row as $column)
            {
                echo("<td>" . $column . "</td>");
            }
            echo("</tr>");
        }
</code>```

If this is not what you want you have to clarify, in your question, what you really want.

Title: Dynamic View of a SQL Table in php

Body:
my task at he moment is to show the data from a sql db in a browser.
My code is fine for that, but now i have more and bigger sql tables and i am looking for a way to read and show it more dynamic. So that i dont have to write all the names of the column (the echo statements, if i have 100 columns it would not really work like this) in the code. Is there ab better way in this case?

Thanks.

<?php
            error_reporting(E_ALL);

            $db_link = mysqli_connect (MYSQL_HOST,
                           MYSQL_BENUTZER,
                           MYSQL_KENNWORT,
                           MYSQL_DATENBANK);

            if ( $db_link )
            {
                echo('
 Verbindung vorhanden:
');
            }
            else
            {
                    echo('
 Keine Verbindung vorhanden:
');
            }

            $db_res = mysqli_query($db_link, "SELECT AA, B1, C3 FROM tableXYZ")
            or die("Fehler: " . mysqli_error());

            echo("
");
            while($row = mysqli_fetch_array($db_res))
            {
                echo("
");
                echo("" . $row["AA"] . "	");
                echo("" . $row["B1"] . "	");
                echo("" . $row["C3"] . "	");
                echo("
");
            }
            echo("
");

            ?>

Body:
You could use a foreach loop to show all columns. Like this:

        while($row = mysqli_fetch_array($db_res))
        {
            echo("<tr>");
            foreach ($row as $column)
            {
                echo("<td>" . $column . "</td>");
            }
            echo("</tr>");
        }

If this is not what you want you have to clarify, in your question, what you really want.