问:
How to get the number after particular string from array of strings using javascript?
below is an array of strings.

```<code>const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
]
</code>```

now i have to filter strings that has string starting with item/1/ and is not followed by any other string or is ending with string item/1/

so the expected filtered array is like below,

```<code>const filtered_array = [
    "list/1/item/1/",
    "item/2/",
]
</code>```

from this filtered array i want to get only the number after item/ so the expected output is

```<code>const ids = ["1","2"]
</code>```

i have tried below

```<code>var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
            .map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]); //error
            //here
</code>```

this gives output like below

```<code>const output = ["1", "2", "3", "4"]
</code>```

because this matches also strings "item/3/subitem/2/",
"item/4/subitem/3/someother/5",

how can i fix this regex to match only strings starting with item/3/ and not followed by any other string or is ending with item/3/

also i get object is possibly null on map match line. could someone help me fix this. thanks.

答:
It sounds like you want item/<any_number>, but only if it's the last thing in the string. To do that, you'd use /\bitem\/\d+\/$/:

\b means "word break" so we don't match subitem

item matches the word item literally

\/ is how you write a / inside a regex so you match a / literally

\d means "any digit"

+ means "one or more (of those digits)"

\/ is another literal /

$ means "end of input

Since you want to get the number from that, we'd wrap the \d+ in () to make it a capture group. Then either use map to createa  map of either the matched string or undefined and then filter out undefined with filter:

```<code>const rex = /\bitem\/(\d+)\/$/;
const output = arr.map(str => (str.match(rex) ?? [])[1])
    .filter(result => result !== undefined);
</code>```

Live Example:

const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
];
const rex = /\bitem\/(\d+)\/$/;
const output = arr.map(str => (str.match(rex) ?? [])[1])
    .filter(result => result !== undefined);
console.log(output);```
</div>
</div>
</p>
<p>Or make just one pass through the data using a simple loop:</p>
```const rex = /\bitem\/(\d+)\/$/;
const output = [];
for (const str of arr) {
    const match = str.match(rex);
    if (match) {
        output.push(match[1]);
    }
}
```
<p>Live Example:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
];
const rex = /\bitem\/(\d+)\/$/;
const output = [];
for (const str of arr) {
    const match = str.match(rex);
    if (match) {
        output.push(match[1]);
    }
}
console.log(output);</code>```

Note that that would match "sub-item/1/", though. If you want to require that item be either at the beginning of the string or just after a /, we change the \b to (?:^|\/) to say "beginning of string or /" (the (?:___) is just to group the alternation [|]): /(?:^|\/)item\/(\d+)\/$/

Body:
below is an array of strings.

const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
]

now i have to filter strings that has string starting with item/1/ and is not followed by any other string or is ending with string item/1/

so the expected filtered array is like below,

const filtered_array = [
    "list/1/item/1/",
    "item/2/",
]

from this filtered array i want to get only the number after item/ so the expected output is

const ids = ["1","2"]

i have tried below

var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
            .map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]); //error
            //here

this gives output like below

const output = ["1", "2", "3", "4"]

because this matches also strings "item/3/subitem/2/",
"item/4/subitem/3/someother/5",

how can i fix this regex to match only strings starting with item/3/ and not followed by any other string or is ending with item/3/

also i get object is possibly null on map match line. could someone help me fix this. thanks.

Body:
It sounds like you want item/<any_number>, but only if it's the last thing in the string. To do that, you'd use /\bitem\/\d+\/$/:

\b means "word break" so we don't match subitem

item matches the word item literally

\/ is how you write a / inside a regex so you match a / literally

\d means "any digit"

+ means "one or more (of those digits)"

\/ is another literal /

$ means "end of input

Since you want to get the number from that, we'd wrap the \d+ in () to make it a capture group. Then either use map to createa  map of either the matched string or undefined and then filter out undefined with filter:

const rex = /\bitem\/(\d+)\/$/;
const output = arr.map(str => (str.match(rex) ?? [])[1])
    .filter(result => result !== undefined);

Live Example:

const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
];
const rex = /\bitem\/(\d+)\/$/;
const output = arr.map(str => (str.match(rex) ?? [])[1])
    .filter(result => result !== undefined);
console.log(output);

Or make just one pass through the data using a simple loop:

const rex = /\bitem\/(\d+)\/$/;
const output = [];
for (const str of arr) {
    const match = str.match(rex);
    if (match) {
        output.push(match[1]);
    }
}

Live Example:

const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
];
const rex = /\bitem\/(\d+)\/$/;
const output = [];
for (const str of arr) {
    const match = str.match(rex);
    if (match) {
        output.push(match[1]);
    }
}
console.log(output);

Note that that would match "sub-item/1/", though. If you want to require that item be either at the beginning of the string or just after a /, we change the \b to (?:^|\/) to say "beginning of string or /" (the (?:___) is just to group the alternation [|]): /(?:^|\/)item\/(\d+)\/$/


来源: stackexchange

问:
Flutter Integration test failed when using tester.enterText more than 2 times
If I run this code snippet:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
</code>```

or this one:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
</code>```

It both works.

But if I run the three:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
</code>```

The test will fail and produce this error:

```<code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element

When the exception was thrown, this was the stack:
#0      Iterable.single (dart:core/iterable.dart:654:25)
#1      WidgetController.state (package:flutter_test/src/controller.dart:156:42)
#2      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1042:42)
#3      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1041:39)
#6      TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#7      WidgetTester.showKeyboard (package:flutter_test/src/widget_tester.dart:1041:27)
#8      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1077:13)
#9      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1076:39)
#12     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#13     WidgetTester.enterText (package:flutter_test/src/widget_tester.dart:1076:27)
#14     AddAccountScreenRobot.enterAccountDetails (file:///C:/Users/Noyruto/sources/repos/account_saver/integration_test/robots/add_account_screen_robot.dart:25:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from dart:async and package:stack_trace)
</code>```

答:
I just solved my own problem.
Because the TextFields are inside ListView widget and when the screen key shows up, other TextField widget is not visible. So what I did was scroll down the form using tester.fling() to make the password TextField visible.

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.pumpAndSettle();
await tester.fling(listFinder, const Offset(0, -500), 10000);
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
await tester.pump(Duration(seconds: 2));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I run this code snippet:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');

or this one:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');

It both works.

But if I run the three:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');

The test will fail and produce this error:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element

When the exception was thrown, this was the stack:
#0      Iterable.single (dart:core/iterable.dart:654:25)
#1      WidgetController.state (package:flutter_test/src/controller.dart:156:42)
#2      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1042:42)
#3      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1041:39)
#6      TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#7      WidgetTester.showKeyboard (package:flutter_test/src/widget_tester.dart:1041:27)
#8      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1077:13)
#9      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1076:39)
#12     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#13     WidgetTester.enterText (package:flutter_test/src/widget_tester.dart:1076:27)
#14     AddAccountScreenRobot.enterAccountDetails (file:///C:/Users/Noyruto/sources/repos/account_saver/integration_test/robots/add_account_screen_robot.dart:25:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from dart:async and package:stack_trace)

Body:
I just solved my own problem.
Because the TextFields are inside ListView widget and when the screen key shows up, other TextField widget is not visible. So what I did was scroll down the form using tester.fling() to make the password TextField visible.

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.pumpAndSettle();
await tester.fling(listFinder, const Offset(0, -500), 10000);
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
await tester.pump(Duration(seconds: 2));


问:
NameError: name '_mysql' is not defined after setting change to mysql
I have a running Django blog with sqlite3 db at my local machine. What I want is to

convert sqlite3 db to mysql db

change Django settings.py file to serve MySQL db

Before I ran into the first step, I jumped into the second first. I followed this web page (on MacOS). I created databases called djangolocaldb on root user and have those infos in /etc/mysql/my.cnf like this:

```<code># /etc/mysql/my.cnf

[client]
database=djangolocaldb
user=root
password=ROOTPASSWORD
default-character-set=utf8
</code>```

Of course I created db, but not table within it.

```<code>mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| djangolocaldb      |
| employees          |
| information_schema |
| mydatabase         |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)
</code>```

I changed settings.py like this as the web page suggested. Here's how:

```<code># settings.py

...

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'OPTIONS' : {
                'read_default_file': '/etc/mysql/my.cnf',
                }
            }
        }

...
</code>```

Now, when I run python manage.py runserver with my venv activated, I got a brutal traceback like this(I ran python manage.py migrate first, and the traceback looked almost the same anyway):

```<code>(.venv) ➜  django-local-blog git:(master) ✗ python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: dlopen(/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib
  Referenced from: /Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so
  Reason: image not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/base.py", line 121, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/options.py", line 208, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/utils.py", line 207, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module>
    import MySQLdb as Database
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module>
    version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
</code>```

So this NameError: name '_mysql' is not defined is the problem. I installed mysqlclient before, changed settings.py, made db in mysql, but none of the steps made it any helpful yet.

And I noticed that even I changed my settings.py back to sqlite3, my blog spit the same _mysql not defined error. So I ended up reverting my commit and now I'm back to sqlite3 (at least my blog is running with it).

I'm guessing it could be that I didn't convert data first, but I'm not 100% sure of it.

Any suggestion would be much appreciated. Thank you in advance!

答:
although I used _mysql for 10 years, the MySQL website tells the recommended way for Python 3 at:
https://dev.mysql.com/doc/connector-python/en/preface.html

Conversion may take some time, but for me less than an hour. Here an example with new code:

```<code>import mysql.connector
cnx = mysql.connector.connect(user='mensfort', password='zhongcan',
                              host='127.0.0.1', database='restaurant')
cursor = cnx.cursor()
cursor.execute('select dongle from personnel')
for dongle in cursor:
    print(dongle)
cursor.close()
cnx.close()
</code>```

Please use your own password, database name, queries, this is just an example.

Please do UNINSTALL this. This is not working for me:

```<code>pip uninstall mysql-connector
</code>```

Please INSTALL this first. It works great:

```<code>pip install mysql-connector-python
</code>```

Body:
I have a running Django blog with sqlite3 db at my local machine. What I want is to

convert sqlite3 db to mysql db

change Django settings.py file to serve MySQL db

Before I ran into the first step, I jumped into the second first. I followed this web page (on MacOS). I created databases called djangolocaldb on root user and have those infos in /etc/mysql/my.cnf like this:

# /etc/mysql/my.cnf

[client]
database=djangolocaldb
user=root
password=ROOTPASSWORD
default-character-set=utf8

Of course I created db, but not table within it.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| djangolocaldb      |
| employees          |
| information_schema |
| mydatabase         |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)

I changed settings.py like this as the web page suggested. Here's how:

# settings.py

...

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'OPTIONS' : {
                'read_default_file': '/etc/mysql/my.cnf',
                }
            }
        }

...

Now, when I run python manage.py runserver with my venv activated, I got a brutal traceback like this(I ran python manage.py migrate first, and the traceback looked almost the same anyway):

(.venv) ➜  django-local-blog git:(master) ✗ python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: dlopen(/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib
  Referenced from: /Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so
  Reason: image not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/base.py", line 121, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/models/options.py", line 208, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/utils.py", line 207, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/Users/gwanghyeongim/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module>
    import MySQLdb as Database
  File "/Users/gwanghyeongim/Documents/py/coreyMS_pj/django-local-blog/.venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module>
    version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined

So this NameError: name '_mysql' is not defined is the problem. I installed mysqlclient before, changed settings.py, made db in mysql, but none of the steps made it any helpful yet.

And I noticed that even I changed my settings.py back to sqlite3, my blog spit the same _mysql not defined error. So I ended up reverting my commit and now I'm back to sqlite3 (at least my blog is running with it).

I'm guessing it could be that I didn't convert data first, but I'm not 100% sure of it.

Any suggestion would be much appreciated. Thank you in advance!

Body:
although I used _mysql for 10 years, the MySQL website tells the recommended way for Python 3 at:
https://dev.mysql.com/doc/connector-python/en/preface.html

Conversion may take some time, but for me less than an hour. Here an example with new code:

import mysql.connector
cnx = mysql.connector.connect(user='mensfort', password='zhongcan',
                              host='127.0.0.1', database='restaurant')
cursor = cnx.cursor()
cursor.execute('select dongle from personnel')
for dongle in cursor:
    print(dongle)
cursor.close()
cnx.close()

Please use your own password, database name, queries, this is just an example.

Please do UNINSTALL this. This is not working for me:

pip uninstall mysql-connector

Please INSTALL this first. It works great:

pip install mysql-connector-python


问:
General Techniques for Locking or Synchronizing UI/Model/Disk for Cloud Support
I'm implementing a cloud synchronization method in a shoebox application under Mac OS X Lion, and I'm (as expected) quickly running into threading/synchronization problems.

There are a number of components to the application, but I'm feeling a bit overwhelmed trying to prevent deadlocks while at the same time maintaining good separation between the pieces.

For example, my app has a few critical behaviors:

Saves to disk periodically and when a model change occurs. (To support Automatic/Sudden Termination under OS X Lion.)

Is periodically notified when a new serialized model is available on disk.

Updates the UI when a model on disk is loaded into memory, or when notified of any model changes have been made that were not caused by user actions.

Here's a sample use case that causes temporary brain hurt:

User is viewing a list of model items in the application.

Simultaneously, application is notified of a new model on disk. Application loads the model into memory, storing into a temporary variable.

How can the application swap out the old hierarchical data model with the new one, without corrupting the UI thread? For example, there's a main RootElement object, with many ChildElement elements. If the UI thread is iterating over myRootElement.children, how can the myRootElement object be replaced without interfering? (Eg. mutating a list while being enumerated.)

More than a specific solution, I'm looking for any previous resources/techniques/paradigms to help design an app around this kind of concurrency and thread safety.

答:
The apple dev docs are pretty good on this subject.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html

You will need some NSLock knowledge, in particular. It seems NSLock is the nearest equivalent to a Mutex, or CriticalSection if you know those terms.

ContentLicense: CC BY-SA 3.0


问:
SwiftUI Image clipsToBounds
Experimenting with SwiftUI (Xcode 11.0 beta 2), I try to fill a View with an image :

```<code>Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
    .border(Color.black)
</code>```

This renders like so :

I would like to apply something similar to UIView.clipsToBounds so the image is clipped and the parts outside of the box are not visible.

答:
```<code>Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
+   .contentShape(Rectangle())
+   .clipped()
    .border(Color.black)
</code>```

This helped me fixing the issue by image overlapping a button. contentShape() was used to clip hit-testing area.
clipped() is clipping the contents inside the view's bounds(as others mentioned).

Title: SwiftUI Image clipsToBounds

Body:
Experimenting with SwiftUI (Xcode 11.0 beta 2), I try to fill a View with an image :

Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
    .border(Color.black)

This renders like so :

I would like to apply something similar to UIView.clipsToBounds so the image is clipped and the parts outside of the box are not visible.

Body:
Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
+   .contentShape(Rectangle())
+   .clipped()
    .border(Color.black)

This helped me fixing the issue by image overlapping a button. contentShape() was used to clip hit-testing area.
clipped() is clipping the contents inside the view's bounds(as others mentioned).


问:
Making a button to control the background image in Javascript
I'm trying to make a button you can press on the webpage that will change its background with a snow gif I prepared. I got the button to show and hide the gif and even append it, but can't seem to make it change the full background to make it seem like it started snowing. Here's the code for that:

```<code>function snowing(){
            let x = document.getElementById('hideimage');
            document.getElementById('sno_btn').onclick = function(){
                if (x.style.display === "none") {
                    x.style.display = "block";
                    document.body.style.backgroundImage = "url('snow.gif') no repeat scroll center";
                } else {
                    x.style.display = "none";
                    document.body.style.background = "black";
                }
        }
</code>```

Right now, I just have the gif hidden on the page until I need it.
If someone can point me in the right direction, if I can achieve this with Javascript or not, or if I should be looking deeper?

答:
change this

```<code>if (x.style.display === "none") {
                x.style.display = "block";
                document.body.style.backgroundImage = "url('snow.gif') no repeat scroll center";
            } else {
                x.style.display = "none";
                document.body.style.background = "black";
            }
</code>```

to

```<code>if (getComputedStyle(x).display === "none") {
                x.style.display = "block";
                document.body.style.background = "url('snow.gif') no repeat scroll center";
            } else {
                x.style.display = "none";
                document.body.style.background = "black";
            }
</code>```

pls tell me if that works

Body:
I'm trying to make a button you can press on the webpage that will change its background with a snow gif I prepared. I got the button to show and hide the gif and even append it, but can't seem to make it change the full background to make it seem like it started snowing. Here's the code for that:

function snowing(){
            let x = document.getElementById('hideimage');
            document.getElementById('sno_btn').onclick = function(){
                if (x.style.display === "none") {
                    x.style.display = "block";
                    document.body.style.backgroundImage = "url('snow.gif') no repeat scroll center";
                } else {
                    x.style.display = "none";
                    document.body.style.background = "black";
                }
        }

Right now, I just have the gif hidden on the page until I need it.
If someone can point me in the right direction, if I can achieve this with Javascript or not, or if I should be looking deeper?

Body:
change this

if (x.style.display === "none") {
                x.style.display = "block";
                document.body.style.backgroundImage = "url('snow.gif') no repeat scroll center";
            } else {
                x.style.display = "none";
                document.body.style.background = "black";
            }

to

if (getComputedStyle(x).display === "none") {
                x.style.display = "block";
                document.body.style.background = "url('snow.gif') no repeat scroll center";
            } else {
                x.style.display = "none";
                document.body.style.background = "black";
            }

pls tell me if that works


问:
Openlayers GeoJSON is at the wrong place
I'm new to Openlayers and have little experience with leaflet. A GeoJSON which worked in leaflet is at the completly wrong place (little red dot)

I can understand that it has something to do with projection, but as i'm new i could not find a working projection. As the GeoJSON worked perfectly in leaflet, i'm assuming its EPSG:3857 the file can be found here

and if you zoom very far in, it is projected

```<code>import React, { useEffect, useState } from 'react'
import isDefined from '../../lib/utils/is-defined'
import OlMap from 'ol/Map'
import OlView from 'ol/View'
import OlLayerTile from 'ol/layer/Tile'
import OlSourceOSM from 'ol/source/Osm'
import GeoJSON from 'ol/format/GeoJSON'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'
import germanyFullGeoJSON from '../../assets/germany_full.json'
import 'ol/ol.css'

const styles = {
  MultiPolygon: new Style({
    stroke: new Stroke({
      color: 'red',
      width: 4
    }),
    fill: new Fill({
      color: 'red'
    })
  })
}

const styleFunction = function (feature) {
  return styles[feature.getGeometry().getType()]
}

const Map = () => {
  const [map, setMap] = useState(null)
  const [zoom, setZoom] = useState(5)
  const [center, setCenter] = useState([546000, 6868000])

  useEffect(() => {
    const format = new GeoJSON()
    const features = format.readFeatures(germanyFullGeoJSON)

    const vectorLayer = new VectorLayer({
      source: new VectorSource({
        features
      }),
      style: styleFunction
    })
    const tempMap = new OlMap({
      target: 'map',
      layers: [
        new OlLayerTile({
          source: new OlSourceOSM()
        }),
        vectorLayer
      ],
      view: new OlView({
        center,
        zoom
      })

    })
    setMap(tempMap)
  }, [])

  if (isDefined(map)) {
    map.getView().setCenter(center)
    map.getView().setZoom(zoom)
    map.render()
  }
  return (
    <div id="map" style={{ width: '100%', height: '100%' }} />
  )
}

export default Map
</code>```

答:
The default projection of OpenLayers is EPSG:3857. Therefore you need to transform your GeoJSON feature of Germany, which is given in EPSG:4326. Try to fix format as follow setting featureProjection accordingly:

```<code>const format = new GeoJSON({ featureProjection: 'EPSG:3857' });
</code>```

Body:
I'm new to Openlayers and have little experience with leaflet. A GeoJSON which worked in leaflet is at the completly wrong place (little red dot)

I can understand that it has something to do with projection, but as i'm new i could not find a working projection. As the GeoJSON worked perfectly in leaflet, i'm assuming its EPSG:3857 the file can be found here

and if you zoom very far in, it is projected

import React, { useEffect, useState } from 'react'
import isDefined from '../../lib/utils/is-defined'
import OlMap from 'ol/Map'
import OlView from 'ol/View'
import OlLayerTile from 'ol/layer/Tile'
import OlSourceOSM from 'ol/source/Osm'
import GeoJSON from 'ol/format/GeoJSON'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'
import germanyFullGeoJSON from '../../assets/germany_full.json'
import 'ol/ol.css'

const styles = {
  MultiPolygon: new Style({
    stroke: new Stroke({
      color: 'red',
      width: 4
    }),
    fill: new Fill({
      color: 'red'
    })
  })
}

const styleFunction = function (feature) {
  return styles[feature.getGeometry().getType()]
}

const Map = () => {
  const [map, setMap] = useState(null)
  const [zoom, setZoom] = useState(5)
  const [center, setCenter] = useState([546000, 6868000])

  useEffect(() => {
    const format = new GeoJSON()
    const features = format.readFeatures(germanyFullGeoJSON)

    const vectorLayer = new VectorLayer({
      source: new VectorSource({
        features
      }),
      style: styleFunction
    })
    const tempMap = new OlMap({
      target: 'map',
      layers: [
        new OlLayerTile({
          source: new OlSourceOSM()
        }),
        vectorLayer
      ],
      view: new OlView({
        center,
        zoom
      })

    })
    setMap(tempMap)
  }, [])

  if (isDefined(map)) {
    map.getView().setCenter(center)
    map.getView().setZoom(zoom)
    map.render()
  }
  return (

  )
}

export default Map

Body:
The default projection of OpenLayers is EPSG:3857. Therefore you need to transform your GeoJSON feature of Germany, which is given in EPSG:4326. Try to fix format as follow setting featureProjection accordingly:

const format = new GeoJSON({ featureProjection: 'EPSG:3857' });


问:
RxSwift Swift - Select/Deselect multiple rows in tableView
I can select rows in tableView.rx but I'm wonder how to get array of final selection. I mean the result array of selecting some rows and then deselecting some rows.

Here's my code:

```<code> Observable.zip(tableView.rx.modelSelected(Country.self), tableView.rx.itemSelected).subscribe(onNext: { (selectedCountry, indexPath) in
            print("2 selected Country is \(selectedCountry) and indexPath is \(indexPath.row)")
            self.selectedCountries.append(selectedCountry)
</code>```

I want also see selected rows as marked.

I appreciate for your helping. thanks

答:
This will produce an Observable array of indexPaths:</p>
```<code>    tableView.allowsMultipleSelection = true

    let selectedItems = Observable.merge(
        tableView.rx.itemSelected.asObservable(),
        tableView.rx.itemDeselected.asObservable()
    )
        .flatMap { [tableView] _ in
            Observable.just(tableView.indexPathsForSelectedRows ?? [])
        }
</code>```

Body:
I can select rows in tableView.rx but I'm wonder how to get array of final selection. I mean the result array of selecting some rows and then deselecting some rows.

Here's my code:

 Observable.zip(tableView.rx.modelSelected(Country.self), tableView.rx.itemSelected).subscribe(onNext: { (selectedCountry, indexPath) in
            print("2 selected Country is \(selectedCountry) and indexPath is \(indexPath.row)")
            self.selectedCountries.append(selectedCountry)

I want also see selected rows as marked.

I appreciate for your helping. thanks

Body:
This will produce an Observable array of indexPaths:

    tableView.allowsMultipleSelection = true

    let selectedItems = Observable.merge(
        tableView.rx.itemSelected.asObservable(),
        tableView.rx.itemDeselected.asObservable()
    )
        .flatMap { [tableView] _ in
            Observable.just(tableView.indexPathsForSelectedRows ?? [])
        }


问:
How to properly `Iscatter` list or numpy array from Python to C++ with mpi4py?
I have worker code written in C++ and manager code in Python.

I call the workers from the manager with MPI.COMM_WORLD.Spawn() and I would like to scatter some data to the workers. Something like this:

from mpi4py import MPI
import os

cpp_mpi_info = MPI.Info.create()
cpp_mpi_info.Set("path", os.getcwd())
inter_comm = MPI.COMM_WORLD.Spawn("./worker", maxprocs=4, info=cpp_mpi_info)
send_buf = [5, 6, 7, 8]
request = inter_comm.Iscatter(send_buf, None, MPI.ROOT)
request.Wait()
```
<p>The worker code looks like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <mpi.h>

int main(int argc, char **argv)
{
    MPI_Comm inter_comm;
    MPI_Init(&argc, &argv);
    MPI_Comm_get_parent(&inter_comm);
    int send_buf;
    int recv_buf;
    MPI_Request request;
    MPI_Iscatter(&send_buf, 1, MPI_INT, &recv_buf, 1, MPI_INT, 0, inter_comm, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
    MPI_Finalize();
    return 0;
}
</code>```

The MPI_Wait() is necessary, because MPI_Iscatter() is non-blocking. But this MPI_Wait() throws a MPI_ERR_TRUNCATE: message truncated error.

So I assume it has something to do with the data preparation on the manager side.

答:
After some back and forth I may have found a solution.

The inter_comm.Iscatter() function needs a buffer for sending. However it is not explicitly explained how to create such a buffer. It was hidden in one of the examples in the PDF User Manual unter section 3.3 Collective communication.

There, they use a Numpy array as send buffer, which is created like this:

send_buf = np.array([5,6,7,8], dtype="i")
```
<p>You can create an empty recive buffer like this:</p>
<pre class="lang-py prettyprint-override"><code>recv_buf = np.empty(4, dtype="i")
</code>```

It is basically the same like creating every Numpy array, but the dtype is very importand. It is not possible to use either one of the Numpy data types (like np.int32, np.float64, np.complex128, etc.) or a Python data type (like int, float, str, etc.). You expicitly have to use the data types represented as string ("i", "u", "f", "c", and so forth). This is because this are the Array Interface data types. I assume this is necessary to make sure a certain memory layout is used so MPI C++ at the reciving end can understand the data.

Body:
I have worker code written in C++ and manager code in Python.

I call the workers from the manager with MPI.COMM_WORLD.Spawn() and I would like to scatter some data to the workers. Something like this:

from mpi4py import MPI
import os

cpp_mpi_info = MPI.Info.create()
cpp_mpi_info.Set("path", os.getcwd())
inter_comm = MPI.COMM_WORLD.Spawn("./worker", maxprocs=4, info=cpp_mpi_info)
send_buf = [5, 6, 7, 8]
request = inter_comm.Iscatter(send_buf, None, MPI.ROOT)
request.Wait()

The worker code looks like this:

#include <mpi.h>

int main(int argc, char **argv)
{
    MPI_Comm inter_comm;
    MPI_Init(&argc, &argv);
    MPI_Comm_get_parent(&inter_comm);
    int send_buf;
    int recv_buf;
    MPI_Request request;
    MPI_Iscatter(&send_buf, 1, MPI_INT, &recv_buf, 1, MPI_INT, 0, inter_comm, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
    MPI_Finalize();
    return 0;
}

The MPI_Wait() is necessary, because MPI_Iscatter() is non-blocking. But this MPI_Wait() throws a MPI_ERR_TRUNCATE: message truncated error.

So I assume it has something to do with the data preparation on the manager side.

Body:
After some back and forth I may have found a solution.

The inter_comm.Iscatter() function needs a buffer for sending. However it is not explicitly explained how to create such a buffer. It was hidden in one of the examples in the PDF User Manual unter section 3.3 Collective communication.

There, they use a Numpy array as send buffer, which is created like this:

send_buf = np.array([5,6,7,8], dtype="i")

You can create an empty recive buffer like this:

recv_buf = np.empty(4, dtype="i")

It is basically the same like creating every Numpy array, but the dtype is very importand. It is not possible to use either one of the Numpy data types (like np.int32, np.float64, np.complex128, etc.) or a Python data type (like int, float, str, etc.). You expicitly have to use the data types represented as string ("i", "u", "f", "c", and so forth). This is because this are the Array Interface data types. I assume this is necessary to make sure a certain memory layout is used so MPI C++ at the reciving end can understand the data.


问:
Google Civic Information API throwing error in Python
I'm trying to utilize pygci to pull voting district data for a particular address. I've enabled the Google Civic Information API for the listed key, but all I'm getting is

"Response was not valid Json"

when I try to run this code:

```<code>*from pygci import GCivicInfo, GCivicInfoError
API_KEY = 'AIzaSyA1EBhUzaHBaaFB8H7LiWfVQsf0KnuwRSs'
address = "4935 Spruce St. Philadelphia, PA 19139"

CivicInfo = GCivicInfo(api_key=API_KEY)
try:
    CivicInfo.get_representative_by_address(params=address)
except GCivicInfoError as e:
    print(e)*
</code>```

答:
Looking at the docs for the underlying API, it ultimately needs the address to have the keyword "address" encoded as a URL parameter:

```<code>GET https://civicinfo.googleapis.com/civicinfo/v2/representatives?address=4935%20Spruce%20St.%20Philadelphia%2C%20PA%2019139&key=your_api_key
</code>```

With the requests library, you encode parameters into the URL this way by passing it a dict. So I was going to suggest you try:

CivicInfo.get_representative_by_address(params={"address": address})
```
<p>But looking at <code>pygci</code>, it appears <code>get_representative_by_address</code> overwrites <code>params</code> with <code>''</code>. If you still get an error, there's may be a bug in the library, or I've misunderstood its code.
https://github.com/moosh3/pygci/blob/f80c336a4417f57ce80495e02f0a4a45eb0f4ce1/pygci/endpoints.py#L33</p>
<pre class="lang-py prettyprint-override"><code>def get_representative_by_address(self, params):
    """Looks up political geography and representative
    information for a single address
    :param address: (optional) type=string
    :param includeOffices: (optional) type=boolean, default=True
    """
    address = ''
    return self.get('/representatives?', params=address)
</code>```

Body:
I'm trying to utilize pygci to pull voting district data for a particular address. I've enabled the Google Civic Information API for the listed key, but all I'm getting is

"Response was not valid Json"

when I try to run this code:

*from pygci import GCivicInfo, GCivicInfoError
API_KEY = 'AIzaSyA1EBhUzaHBaaFB8H7LiWfVQsf0KnuwRSs'
address = "4935 Spruce St. Philadelphia, PA 19139"

CivicInfo = GCivicInfo(api_key=API_KEY)
try:
    CivicInfo.get_representative_by_address(params=address)
except GCivicInfoError as e:
    print(e)*

Body:
Looking at the docs for the underlying API, it ultimately needs the address to have the keyword "address" encoded as a URL parameter:

GET https://civicinfo.googleapis.com/civicinfo/v2/representatives?address=4935%20Spruce%20St.%20Philadelphia%2C%20PA%2019139&key=your_api_key

With the requests library, you encode parameters into the URL this way by passing it a dict. So I was going to suggest you try:

CivicInfo.get_representative_by_address(params={"address": address})

But looking at pygci, it appears get_representative_by_address overwrites params with ''. If you still get an error, there's may be a bug in the library, or I've misunderstood its code.
https://github.com/moosh3/pygci/blob/f80c336a4417f57ce80495e02f0a4a45eb0f4ce1/pygci/endpoints.py#L33

def get_representative_by_address(self, params):
    """Looks up political geography and representative
    information for a single address
    :param address: (optional) type=string
    :param includeOffices: (optional) type=boolean, default=True
    """
    address = ''
    return self.get('/representatives?', params=address)


问:
Accessing information - Array of pointers
```<code>int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);
</code>```

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

答:
```<code>int *b = x;
int *c = y;
</code>```

Why isn't this working?

Because you assign the value held by the integer to the pointer, not the reference of the variable x or y

You need to:

```<code>int *b = &x;
int *c = &y;
</code>```

Body:
int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

Body:
int *b = x;
int *c = y;

Why isn't this working?

Because you assign the value held by the integer to the pointer, not the reference of the variable x or y

You need to:

int *b = &x;
int *c = &y;


问:
Scraping data, appending to list, and making it a dataframe
I am trying to scrape a bunch of baseball statistics and get all that data into separate data Frames so I can use it for my project. I am able to get all of the data, but I am having trouble figuring out how to store all of this data in variables and slice it accordingly.

```<code>def parse_row(rows):
    return [str(x.string)for x in rows.find_all('td')]

def soop(url):
    page = requests.get(url)
    text = soup(page.text, features = 'lxml')
    row = text.find_all('tr')
    data = [parse_row(rows)for rows in row]
    df = pd.DataFrame(data)
    df = df.dropna()
    if dp_num in url:
        df.columns = dp_col
    elif sb_num in url:
        df.columns = sb_col
    elif hr_num in url:
        df.columns = hr_col
    elif obp_num in url:
        df.columns = obp_col
    elif b2_num in url:
        df.columns = b2_col
    elif b3_num in url:
        df.columns = b3_col
    elif era_num in url:
        df.columns = era_col
    elif fld_num in url:
        df.columns = fld_col
    else:
        print('error')
    return(df)

# ncaa scraping function
def scrape(id_num):
    loop = 1
    page_num = 2
    page_numii = 2
    page_numiii = 2
    url = 'https://www.ncaa.com/stats/baseball/d1/current/team/' + id_num
    dii_url = 'https://www.ncaa.com/stats/baseball/d2/current/team/' + id_num
    diii_url = 'https://www.ncaa.com/stats/baseball/d3/current/team/' + id_num
    while loop == 1: #first di page
        df = soop(url)
        loop += 1
        print(df)
    while loop <= 6: #number of remaining di pages
        df = soop(url + '/p' + str(page_num))
        page_num += 1
        loop += 1
        print(df)
    while loop == 7: # first d2 page
        df = soop(dii_url)
        loop += 1
        print(df)
    while loop <= 11:#remaining d2 pages
        df = soop(dii_url + '/p' + str(page_numii))
        page_numii += 1
        loop += 1
        print(df)
    while loop == 12: #first diii page
        df = soop(diii_url)
        loop += 1
        print(df)
    while loop < 20:#remaining d3 pages
        df = soop(diii_url + '/p' + str(page_numiii))
        page_numiii += 1
        loop += 1
        print(df)
</code>```

All of the code works, and I get no errors, but I would like to store the data it prints out in variables instead of printing it out, and then have those as separate data Frames for each stat page I scraped. But I have no clue where to start doing that, I have seen on here that maybe i should try appending it to a list? I am a statistics major in college, and I am pretty new to programming. Any help is appreciated.

答:
To store dataframes into variables, you would have to construct a list or dictionary to store the dataframes.

With that being said, I probably wouldn't store the tables into variables, but rather write to a database or csv files so that you have the data locally available. Otherwise you'd have to run the scrape every time to get the data. Pandas can handle that for you (as well as parse the tables with .read_html()).

Not sure exactly what data you want or how you want it (I'm also surprised to not see an api here to get that data), but this will grab it and store it into folders with the structure of:

```<code>-data
    -d1
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             .csv files
             ...
             ...
    -d2
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             csv files
             ...
             ...
    -d3
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             csv files
             ...
             ...
</code>```

So looks like this:

Code:

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import os

statsIds_dict = {}
for division in [1,2,3]:
    statsIds_dict[f'd{division}'] = {}
    url = f'https://www.ncaa.com/stats/baseball/d{division}/'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    statsIds = soup.find_all('div', {'class':'stats-header__filter'})
    for each in statsIds:
        statsType = each.text.split('\n')[0]
        statsIds_dict[f'd{division}'][statsType] = {}
        options = each.find_all('option')
        for option in options:
            if option['value']:
                statsIds_dict[f'd{division}'][statsType][option.text] = 'https://www.ncaa.com' + option['value']

for division, v1 in statsIds_dict.items():
    for statsType, v2 in v1.items():
        for statTitle, link in v2.items():
            response = requests.get(link)
            soup = BeautifulSoup(response.text, 'html.parser')
            try:
                totPages = int(soup.find('ul', {'class':'stats-pager'}).find_all('li')[-2].text)
            except:
                totPages = 1
            df = pd.read_html(link)[0]
            print(link)
            for page in range(2, totPages+1):
                temp_df = pd.read_html(link + f'/p{page}')[0]
                print(link + f'/p{page}')
                df = df.append(temp_df).reset_index(drop=True)

            path = f'data/{division}/{statsType}'
            # Check whether the specified path exists or not
            isExist = os.path.exists(path)

            if not isExist:

                # Create a new directory because it does not exist
                os.makedirs(path)
                print(f"The data/{division}/{statsType} directory is created!")

            df.to_csv(f'data/{division}/{statsType}/{division}_{statsType}_{statTitle}.csv' , index=False)
            print(f'Saved: {division} {statsType} {statTitle}')
</code>```

Body:
I am trying to scrape a bunch of baseball statistics and get all that data into separate data Frames so I can use it for my project. I am able to get all of the data, but I am having trouble figuring out how to store all of this data in variables and slice it accordingly.

def parse_row(rows):
    return [str(x.string)for x in rows.find_all('td')]

def soop(url):
    page = requests.get(url)
    text = soup(page.text, features = 'lxml')
    row = text.find_all('tr')
    data = [parse_row(rows)for rows in row]
    df = pd.DataFrame(data)
    df = df.dropna()
    if dp_num in url:
        df.columns = dp_col
    elif sb_num in url:
        df.columns = sb_col
    elif hr_num in url:
        df.columns = hr_col
    elif obp_num in url:
        df.columns = obp_col
    elif b2_num in url:
        df.columns = b2_col
    elif b3_num in url:
        df.columns = b3_col
    elif era_num in url:
        df.columns = era_col
    elif fld_num in url:
        df.columns = fld_col
    else:
        print('error')
    return(df)

# ncaa scraping function
def scrape(id_num):
    loop = 1
    page_num = 2
    page_numii = 2
    page_numiii = 2
    url = 'https://www.ncaa.com/stats/baseball/d1/current/team/' + id_num
    dii_url = 'https://www.ncaa.com/stats/baseball/d2/current/team/' + id_num
    diii_url = 'https://www.ncaa.com/stats/baseball/d3/current/team/' + id_num
    while loop == 1: #first di page
        df = soop(url)
        loop += 1
        print(df)
    while loop <= 6: #number of remaining di pages
        df = soop(url + '/p' + str(page_num))
        page_num += 1
        loop += 1
        print(df)
    while loop == 7: # first d2 page
        df = soop(dii_url)
        loop += 1
        print(df)
    while loop <= 11:#remaining d2 pages
        df = soop(dii_url + '/p' + str(page_numii))
        page_numii += 1
        loop += 1
        print(df)
    while loop == 12: #first diii page
        df = soop(diii_url)
        loop += 1
        print(df)
    while loop < 20:#remaining d3 pages
        df = soop(diii_url + '/p' + str(page_numiii))
        page_numiii += 1
        loop += 1
        print(df)

All of the code works, and I get no errors, but I would like to store the data it prints out in variables instead of printing it out, and then have those as separate data Frames for each stat page I scraped. But I have no clue where to start doing that, I have seen on here that maybe i should try appending it to a list? I am a statistics major in college, and I am pretty new to programming. Any help is appreciated.

Body:
To store dataframes into variables, you would have to construct a list or dictionary to store the dataframes.

With that being said, I probably wouldn't store the tables into variables, but rather write to a database or csv files so that you have the data locally available. Otherwise you'd have to run the scrape every time to get the data. Pandas can handle that for you (as well as parse the tables with .read_html()).

Not sure exactly what data you want or how you want it (I'm also surprised to not see an api here to get that data), but this will grab it and store it into folders with the structure of:

-data
    -d1
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             .csv files
             ...
             ...
    -d2
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             csv files
             ...
             ...
    -d3
        -INDIVIDUAL STATISTICS
             csv files
             ...
             ...
        -TEAM STATISTICS
             csv files
             ...
             ...

So looks like this:

Code:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import os

statsIds_dict = {}
for division in [1,2,3]:
    statsIds_dict[f'd{division}'] = {}
    url = f'https://www.ncaa.com/stats/baseball/d{division}/'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    statsIds = soup.find_all('div', {'class':'stats-header__filter'})
    for each in statsIds:
        statsType = each.text.split('\n')[0]
        statsIds_dict[f'd{division}'][statsType] = {}
        options = each.find_all('option')
        for option in options:
            if option['value']:
                statsIds_dict[f'd{division}'][statsType][option.text] = 'https://www.ncaa.com' + option['value']

for division, v1 in statsIds_dict.items():
    for statsType, v2 in v1.items():
        for statTitle, link in v2.items():
            response = requests.get(link)
            soup = BeautifulSoup(response.text, 'html.parser')
            try:
                totPages = int(soup.find('ul', {'class':'stats-pager'}).find_all('li')[-2].text)
            except:
                totPages = 1
            df = pd.read_html(link)[0]
            print(link)
            for page in range(2, totPages+1):
                temp_df = pd.read_html(link + f'/p{page}')[0]
                print(link + f'/p{page}')
                df = df.append(temp_df).reset_index(drop=True)

            path = f'data/{division}/{statsType}'
            # Check whether the specified path exists or not
            isExist = os.path.exists(path)

            if not isExist:

                # Create a new directory because it does not exist
                os.makedirs(path)
                print(f"The data/{division}/{statsType} directory is created!")

            df.to_csv(f'data/{division}/{statsType}/{division}_{statsType}_{statTitle}.csv' , index=False)
            print(f'Saved: {division} {statsType} {statTitle}')


问:
Python read CSV file with quotes and remove them for further use
I am reading in a CSV file using python like this...

```<code>CSV File
"sku","title","category","description"
73,"clothes","trouser","This is a pair of trousers, it has pockets"

with open(filename) as csv_file:

    reader= csv.reader(csv_file, delimiter=',')

    for sku, title, category, description in reader:

        print(sku)
        print(title)
        print(category)
        print(description)
</code>```

This gives me the following,,

```<code>73
"clothes"
"trouser"
"This is a pair of trousers, it has pockets"
</code>```

I want to take these values and use them for something else, but the quotes are now a problem, I obviously need them in the initial read to make sure that the commas are not seen as a new item.

But what is the best way to strip them now so I can use them elsewhere?

答:
Use quoting parameter with csv.QUOTE_MINIMAL. Prefer use, DictReader because your file has headers:

```<code>with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile, quoting=csv.QUOTE_MINIMAL)
    for d in reader:
        print(d)
</code>```

Output:

```<code>{'sku': '73', 'title': 'clothes', 'category': 'trouser',
 'description': 'This is a pair of trousers, it has pockets'}
</code>```

You can also use csv.QUOTE_NONNUMERIC to get numeric values (see 'sku' entry):

```<code>with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
    for d in reader:
        print(d)

# Output
{'sku': 73.0, 'title': 'clothes', 'category': 'trouser',
 'description': 'This is a pair of trousers, it has pockets'}
</code>```

Body:
I am reading in a CSV file using python like this...

CSV File
"sku","title","category","description"
73,"clothes","trouser","This is a pair of trousers, it has pockets"

with open(filename) as csv_file:

    reader= csv.reader(csv_file, delimiter=',')

    for sku, title, category, description in reader:

        print(sku)
        print(title)
        print(category)
        print(description)

This gives me the following,,

73
"clothes"
"trouser"
"This is a pair of trousers, it has pockets"

I want to take these values and use them for something else, but the quotes are now a problem, I obviously need them in the initial read to make sure that the commas are not seen as a new item.

But what is the best way to strip them now so I can use them elsewhere?

Body:
Use quoting parameter with csv.QUOTE_MINIMAL. Prefer use, DictReader because your file has headers:

with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile, quoting=csv.QUOTE_MINIMAL)
    for d in reader:
        print(d)

Output:

{'sku': '73', 'title': 'clothes', 'category': 'trouser',
 'description': 'This is a pair of trousers, it has pockets'}

You can also use csv.QUOTE_NONNUMERIC to get numeric values (see 'sku' entry):

with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
    for d in reader:
        print(d)

# Output
{'sku': 73.0, 'title': 'clothes', 'category': 'trouser',
 'description': 'This is a pair of trousers, it has pockets'}


问:
how to pass parameter from backend to frontend if don't use hidden field control or any display:none html item
For example, if I want to pass session value to the frontend and use as a variable value in javascript, is there a way that don't use hidden field to pass the value?</p>

答:
Simple way:

```<code> <script type="text/javascript">
        var value = '<%=Session("sessionkey") %>';
 </script>
</code>```

Drawback is that "value" javascript variable will always be string. Event if object stored in session under "sessionkey" is not string. So better way is to use javascript serializer:

```<code> <script type="text/javascript">
        var value = <%=(New System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(Session("sessionkey"))%>;
  </script>
</code>```

Note: you have to reference System.Web.Extensions assembly to use JavaScriptSerializer. Code above is in VB language. C# equivalent would be:

```<code><script type="text/javascript">
            var value = '<%=Session["sessionkey"] %>';
  </script>
</code>```

and

```<code><script type="text/javascript">
            var value = <%=(new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(Session["sessionkey"])%>;
 </script>
</code>```

Body:
Simple way:

 <script type="text/javascript">
        var value = '<%=Session("sessionkey") %>';
 </script>

Drawback is that "value" javascript variable will always be string. Event if object stored in session under "sessionkey" is not string. So better way is to use javascript serializer:

 <script type="text/javascript">
        var value = <%=(New System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(Session("sessionkey"))%>;
  </script>

Note: you have to reference System.Web.Extensions assembly to use JavaScriptSerializer. Code above is in VB language. C# equivalent would be:

<script type="text/javascript">
            var value = '<%=Session["sessionkey"] %>';
  </script>

and

<script type="text/javascript">
            var value = <%=(new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(Session["sessionkey"])%>;
 </script>


问:
How to apply a Select Case statement?
Why does the Select Case statement show the message "No"?

It should be "Bubble".

Sub Macro1()
Dim Resolução As Integer
Resolução = 7

Select Case Resolução
    Case Resolução = 0, 2, 3, 4, 5, 6
        MsgBox ("Ghost")

    Case Resolução = 1
        MsgBox ("Car")

    Case Resolução = 7, 8
        MsgBox ("Bubble")

    Case Else
        MsgBox ("No")

End Select
End Sub
```

答:
You are using the wrong syntax for the cases.

Rather than

```<code>Case Resolução = 0, 2, 3, 4, 5, 6
</code>```

use

```<code>Case 0, 2, 3, 4, 5, 6
</code>```

And similarly for the other cases.

With what you are doing, you are using a Boolean value (the result of a comparison such as Resolução = 0) as a case label.

Title: How to apply a Select Case statement?

Body:
You are using the wrong syntax for the cases.

Rather than

Case Resolução = 0, 2, 3, 4, 5, 6

use

Case 0, 2, 3, 4, 5, 6

And similarly for the other cases.

With what you are doing, you are using a Boolean value (the result of a comparison such as Resolução = 0) as a case label.


问:
How do I get real path as string in Grails
Developed project using grails-3.3.1 and generated a Runnable WAR file. When I run using the command:

```<code>java -jar build/libs/myproject-0.1.war
</code>```

It is returning null for the following line:

```<code>serveltContext.getRealPath("/someSource");
</code>```

But it is working fine when deployed in a Tomcat Container.

Then tried the following way:

```<code>servletContext.getResource("someSource").getPath();
</code>```

It is returning, but not the one as expected and not what getRealPath() returns.
It is returning like this:

```<code>D:/myprojects/myproject/build/libs/myproject-01.war*/
</code>```

which serves no use for me. Found answers suggesting to use getResourceAsStream() but I don't want a resource, I want only String.

答:
I had the same issue with Grails 4.0.11. Seems like serveltContext.getRealPath is deprecated and returns null. Your solution didn't work either for me, so I decided to go with the following approach:
(found on https://howtodoinjava.com/spring-boot2/read-file-from-resources/)

```<code>  import org.springframework.core.io.ClassPathResource
  import org.springframework.core.io.Resource

  Resource resource = new ClassPathResource("pdfResources/fonts/SFUIText-Medium.ttf")
  String path = resource?.getPath()
</code>```

Given the fact, that my app is called "filetest", the file is located on filetest/src/main/resources/pdfResources/fonts/SFUIText-Medium.ttf

This works with "grails run-app" and "grails war" as embedded runnable war file. Hope it helps, as it took me quite a while.

Body:
Developed project using grails-3.3.1 and generated a Runnable WAR file. When I run using the command:

java -jar build/libs/myproject-0.1.war

It is returning null for the following line:

serveltContext.getRealPath("/someSource");

But it is working fine when deployed in a Tomcat Container.

Then tried the following way:

servletContext.getResource("someSource").getPath();

It is returning, but not the one as expected and not what getRealPath() returns.
It is returning like this:

D:/myprojects/myproject/build/libs/myproject-01.war*/

which serves no use for me. Found answers suggesting to use getResourceAsStream() but I don't want a resource, I want only String.

Body:
I had the same issue with Grails 4.0.11. Seems like serveltContext.getRealPath is deprecated and returns null. Your solution didn't work either for me, so I decided to go with the following approach:
(found on https://howtodoinjava.com/spring-boot2/read-file-from-resources/)

  import org.springframework.core.io.ClassPathResource
  import org.springframework.core.io.Resource

  Resource resource = new ClassPathResource("pdfResources/fonts/SFUIText-Medium.ttf")
  String path = resource?.getPath()

Given the fact, that my app is called "filetest", the file is located on filetest/src/main/resources/pdfResources/fonts/SFUIText-Medium.ttf

This works with "grails run-app" and "grails war" as embedded runnable war file. Hope it helps, as it took me quite a while.


问:
Delete lines of tab separated file with date older than 21 days - Powershell
I have multiple .csv files looking something like this which is tab-separated:

```<code>Call ID Latitude    Longitude   Date and Time   wasd
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 wasd
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 wasd
wasd    12.1241234  12.1243 2022-1-15 07:45:13.123  wasd
wasd    12.1241234  12.1243 2022-2-15 07:45:13.123  wasd
wasd    12.1241234  12.1243 2022-2-15 07:45:13.123  wasd
</code>```

Using powershell I need to delete all the lines of the file with a date older than 21 days.
unfortunately im limited to use Powershell only. Any Powershell experts out there?

答:
In other words, you need to only keep the rows that have a 'Date and Time' newer or equal than 21 days ago
To do that, use a Where-Object clause to filter on only the rows you want to keep:

```<code># get the reference date set to midnight
$threeWeeksAgo = (Get-Date).AddDays(-21).Date
Import-Csv -Path 'D:\Test\Blah.tsv' -Delimiter "`t" |
# pass rows newer or equal than 21 days ago
Where-Object { [datetime]$_.'Date and Time' -ge $threeWeeksAgo } |
# write out to (new) file
Export-Csv -Path 'D:\Test\CleanedUpBlah.tsv' -Delimiter "`t" -NoTypeInformation
</code>```

On my Dutch machine, [datetime]$_.'Date and Time' parses the dates correctly, but depending on your system's locale (date & time culture settings) you may need to use

[datetime]::ParseExact($_.'Date and Time', 'yyyy-MM-dd HH:mm:ss.fff', $null)

Since your CSV file is TAB delimited, I'm using extension .tsv (Tab Separated Values) but the code will accept any extension you have given it.

Result on screen using your example:

```<code>Call ID Latitude   Longitude Date and Time          wasd
------- --------   --------- -------------          ----
wasd    12.1241234 12.1243   2022-2-15 07:45:13.123 wasd
wasd    12.1241234 12.1243   2022-2-15 07:45:13.123 wasd
</code>```

If, as you have commented, you would also like have a csv containing the rows that were removed with the above code, you could do this:

```<code># get the reference date set to midnight
$threeWeeksAgo = (Get-Date).AddDays(-21).Date
$fileToCleanUp = 'D:\Test\Blah.tsv'
Import-Csv -Path $fileToCleanUp -Delimiter "`t" |
# pass rows older than 21 days ago
Where-Object { [datetime]$_.'Date and Time' -lt $threeWeeksAgo } |
# add a property with the file name where this line is removed
Select-Object @{Name = 'DeletedFrom'; Expression = {$fileToCleanUp}}, * |
# write out to (new) file
Export-Csv -Path 'D:\Test\RemovedFromBlah.tsv' -Delimiter "`t" -NoTypeInformation
</code>```

Result on screen using your example:

```<code>DeletedFrom      Call ID Latitude   Longitude Date and Time           wasd
-----------      ------- --------   --------- -------------           ----
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2021-12-15 07:45:13.123 wasd
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2021-12-15 07:45:13.123 wasd
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2022-1-15 07:45:13.123  wasd
</code>```

Body:
I have multiple .csv files looking something like this which is tab-separated:

Call ID Latitude    Longitude   Date and Time   wasd
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 wasd
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 wasd
wasd    12.1241234  12.1243 2022-1-15 07:45:13.123  wasd
wasd    12.1241234  12.1243 2022-2-15 07:45:13.123  wasd
wasd    12.1241234  12.1243 2022-2-15 07:45:13.123  wasd

Using powershell I need to delete all the lines of the file with a date older than 21 days.
unfortunately im limited to use Powershell only. Any Powershell experts out there?

Body:
In other words, you need to only keep the rows that have a 'Date and Time' newer or equal than 21 days ago
To do that, use a Where-Object clause to filter on only the rows you want to keep:

# get the reference date set to midnight
$threeWeeksAgo = (Get-Date).AddDays(-21).Date
Import-Csv -Path 'D:\Test\Blah.tsv' -Delimiter "`t" |
# pass rows newer or equal than 21 days ago
Where-Object { [datetime]$_.'Date and Time' -ge $threeWeeksAgo } |
# write out to (new) file
Export-Csv -Path 'D:\Test\CleanedUpBlah.tsv' -Delimiter "`t" -NoTypeInformation

On my Dutch machine, [datetime]$_.'Date and Time' parses the dates correctly, but depending on your system's locale (date & time culture settings) you may need to use

[datetime]::ParseExact($_.'Date and Time', 'yyyy-MM-dd HH:mm:ss.fff', $null)

Since your CSV file is TAB delimited, I'm using extension .tsv (Tab Separated Values) but the code will accept any extension you have given it.

Result on screen using your example:

Call ID Latitude   Longitude Date and Time          wasd
------- --------   --------- -------------          ----
wasd    12.1241234 12.1243   2022-2-15 07:45:13.123 wasd
wasd    12.1241234 12.1243   2022-2-15 07:45:13.123 wasd

If, as you have commented, you would also like have a csv containing the rows that were removed with the above code, you could do this:

# get the reference date set to midnight
$threeWeeksAgo = (Get-Date).AddDays(-21).Date
$fileToCleanUp = 'D:\Test\Blah.tsv'
Import-Csv -Path $fileToCleanUp -Delimiter "`t" |
# pass rows older than 21 days ago
Where-Object { [datetime]$_.'Date and Time' -lt $threeWeeksAgo } |
# add a property with the file name where this line is removed
Select-Object @{Name = 'DeletedFrom'; Expression = {$fileToCleanUp}}, * |
# write out to (new) file
Export-Csv -Path 'D:\Test\RemovedFromBlah.tsv' -Delimiter "`t" -NoTypeInformation

Result on screen using your example:

DeletedFrom      Call ID Latitude   Longitude Date and Time           wasd
-----------      ------- --------   --------- -------------           ----
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2021-12-15 07:45:13.123 wasd
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2021-12-15 07:45:13.123 wasd
D:\Test\Blah.tsv wasd    12.1241234 12.1243   2022-1-15 07:45:13.123  wasd


问:
Malloc Issue : Double free or corruption (out) / Segmentation (core dumped) with Glut OpenGL
i am  currently learning C++ and Glut / OPENGL.
(I don't have the choice I must use Glut even if it's old)
I keep getting errors like :

-Double free or corruption (out)
-Segmentation error (core dumped)
-Corrupted size vs prev_size

The program work sometimes, but most of the times i get these errors.
Please, I need help.

```<code>#include "graph.h"
#include "GLUT.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "eval2.h"

grapheur app;
static int run_once=0;
int x=0;
int i = 0;
double borne_inf=-10;
double borne_sup=100;
double pas=0.01;
double *tabX;
typejeton *tabY;
double *tabYfin, *tabXfin;
int *nb_valeur_ptr=(int*)malloc(sizeof(int));

int setup()
{
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer borne inferieur : (-1000)       |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&borne_inf);
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer borne superieur : (1000)        |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&borne_sup);
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer le pas : (0.01)                 |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&pas);
    // Créer un tableau de X pour avec la fonction evenly(), demander le tableau de y à matis
// , trier le tableau de y pour enlever les erreurs et enlever les antécédents
// normaliser , puis tracer avec la boucle fort //

/// Tableau vide pour matis ///
    int nb_valeur=(borne_sup-borne_inf)/pas;
    //nb_valeur++;
    tabY = (typejeton*) malloc(sizeof(typejeton)*(nb_valeur+1000));
/// tableau de X///
    tabX = (double*) malloc(sizeof(double)*(nb_valeur+1000));
    *nb_valeur_ptr=nb_valeur;
    printf("%d valeurs\n",*nb_valeur_ptr);
    evenly(borne_inf,borne_sup,nb_valeur,tabX);

    Arbre a_test=(Arbre)malloc(sizeof(Arbre));
    a_test->jeton.lexem=FONCTION;
    a_test->jeton.valeur.fonction=EXP;
    Arbre plus=(Arbre)malloc(sizeof(Arbre)),b=(Arbre)malloc(sizeof(Arbre)),c=(Arbre)malloc(sizeof(Arbre));
    a_test->pjeton_gauche=plus;
    plus->jeton.lexem=OPERATEUR;
    plus->jeton.valeur.operateur=PLUS;
    plus->pjeton_gauche=b;
    b->jeton.lexem=REEL;
    b->jeton.valeur.reel=3;
    plus->pjeton_droit=c;
    c->jeton.lexem=VARIABLE;
    //c->jeton.valeur.reel=2;
    Eval(a_test, tabX,*nb_valeur_ptr, tabY);
    return 0;
}

void myKey(int c)
{
    double deplacement = app.echelle*0.25;
    switch (c)
    {
    case 27 :  //touche esc pour quitter
        exit(0);
        break;
    case 'z':
        app.centre.y -= deplacement;
        break;
    case 's':
        app.centre.y += deplacement;
        break;
    case 'q':
        app.centre.x += deplacement;
        break;
    case 'd':
        app.centre.x -= deplacement;
        break;
    case 'p':
        app.echelle = app.echelle / 1.5;
        break;
    case 'm':
        app.echelle = app.echelle * 1.5;
        break;
    case 'f':
        run_once=0;
    case 'Z':
        app.centre.y -= deplacement;
        break;
    case 'S':
        app.centre.y += deplacement;
        break;
    case 'Q':
        app.centre.x += deplacement;
        break;
    case 'D':
        app.centre.x -= deplacement;
        break;
    case 'P':
        app.echelle = app.echelle / 1.5;
        break;
    case 'M':
        app.echelle = app.echelle * 1.5;
        break;
    case 'F':
        run_once=0;
    }
}

void myDraw(void)
{

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    logo_imt();
    setcolor(0.0F, 0.0F, 0.0F);
    axe(app);

    setcolor(0.8f, 0.8f, 0.8f);
//    affiche_graduation(app);

    cartesien p1, p2;

    if (run_once==0)
    {

        setup();
        run_once++;
    }

//      Liste *maListe = initialisation();
   // int tab[5]={0,1,2,3,4};

/*    for (int i=borne_inf;i<borne_sup;i+=pas){
      insertion(maListe,tabY[i]);
    }
    //for (i =borne_inf; i <borne_sup; i +=pas){
    //  if(tabY[i].lexem==ERREUR){

    //}
    //}
    */

    tabXfin = (double*) malloc(sizeof(double) * (*nb_valeur_ptr));
    tabYfin = (double*) malloc(sizeof(double) * (*nb_valeur_ptr));

    while(i < (*nb_valeur_ptr)){
        if(tabY[i].lexem==ERREUR){
            (*nb_valeur_ptr)--;
        }else{
            tabXfin[i]=tabX[i];
            tabYfin[i]=tabY[i].valeur.reel;
            i++;
        }
    }

    for (i =0; i < (*nb_valeur_ptr); i +=1)
    {
        p1.x = tabXfin[i];
        p1.y = tabYfin[i];

        p2.x = tabXfin[i+1];
        p2.y = tabYfin[i+1]; // Remplacer fonction par evalatueur + analyse token
        normalisation(p1, app, &p1);
        normalisation(p2, app, &p2);
        setcolor(0.0F, 1.0F, 0.0F);
        ligne(p1, p2);

    }

    for(int i=0; i<*nb_valeur_ptr; i++)
    {
        (tabY[i].lexem==ERREUR)? printf("marshpa\n") : printf("%lf\n",(tabY+i)->valeur.reel);
    }

}

int main(int ac, char *av[])

{

    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|              Guide de commande                |\n");
    printf("|                                               |\n");
    printf("|-----------------------------------------------|\n");
    printf("|                                               |\n");
    printf("|      - 'z' deplacement vers le haut           |\n");
    printf("|      - 'q' deplacement vers le bas            |\n");
    printf("|      - 's' deplacement vers la gauche         |\n");
    printf("|      - 'd' deplacement vers la droite         |\n");
    printf("|      - 'p' afin de zoomer                     |\n");
    printf("|      - 'm' afin de dezoomer                   |\n");
    printf("|      - 'esc' pour fermer la fenetre           |\n");
    printf("|      - 'f' pour changer les bornes et le pas  |\n");
    printf("-------------------------------------------------\n");

    app.centre.x = 0;
    app.centre.y = 0;
    app.echelle = 5;

    InitGraph(ac, av, "Essai Glut", 640, 480, myDraw, myKey);
    free(tabX);
    free(tabY);
    free(tabXfin);
    free(tabYfin);
    free(nb_valeur_ptr);

    return 0;
}
</code>```

答:
I bet on corruption rather that double free.

If we assume that Arbre is a pointer in Arbre plus=(Arbre)malloc(sizeof(Arbre)), the code allocates space for a pointer, but then uses it as a complete record:

```<code>plus->jeton.lexem=OPERATEUR;
plus->jeton.valeur.operateur=PLUS;
plus->pjeton_gauche=b;
</code>```

This will inevitably overwrite additional memory and corrupt the heap. When later calling free, this corruption is detected.

Body:
i am  currently learning C++ and Glut / OPENGL.
(I don't have the choice I must use Glut even if it's old)
I keep getting errors like :

-Double free or corruption (out)
-Segmentation error (core dumped)
-Corrupted size vs prev_size

The program work sometimes, but most of the times i get these errors.
Please, I need help.

#include "graph.h"
#include "GLUT.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "eval2.h"

grapheur app;
static int run_once=0;
int x=0;
int i = 0;
double borne_inf=-10;
double borne_sup=100;
double pas=0.01;
double *tabX;
typejeton *tabY;
double *tabYfin, *tabXfin;
int *nb_valeur_ptr=(int*)malloc(sizeof(int));

int setup()
{
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer borne inferieur : (-1000)       |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&borne_inf);
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer borne superieur : (1000)        |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&borne_sup);
    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|     - Inserer le pas : (0.01)                 |\n");
    printf("|                                               |\n");
    printf("-------------------------------------------------\n");
    scanf("%lf",&pas);
    // Créer un tableau de X pour avec la fonction evenly(), demander le tableau de y à matis
// , trier le tableau de y pour enlever les erreurs et enlever les antécédents
// normaliser , puis tracer avec la boucle fort //

/// Tableau vide pour matis ///
    int nb_valeur=(borne_sup-borne_inf)/pas;
    //nb_valeur++;
    tabY = (typejeton*) malloc(sizeof(typejeton)*(nb_valeur+1000));
/// tableau de X///
    tabX = (double*) malloc(sizeof(double)*(nb_valeur+1000));
    *nb_valeur_ptr=nb_valeur;
    printf("%d valeurs\n",*nb_valeur_ptr);
    evenly(borne_inf,borne_sup,nb_valeur,tabX);

    Arbre a_test=(Arbre)malloc(sizeof(Arbre));
    a_test->jeton.lexem=FONCTION;
    a_test->jeton.valeur.fonction=EXP;
    Arbre plus=(Arbre)malloc(sizeof(Arbre)),b=(Arbre)malloc(sizeof(Arbre)),c=(Arbre)malloc(sizeof(Arbre));
    a_test->pjeton_gauche=plus;
    plus->jeton.lexem=OPERATEUR;
    plus->jeton.valeur.operateur=PLUS;
    plus->pjeton_gauche=b;
    b->jeton.lexem=REEL;
    b->jeton.valeur.reel=3;
    plus->pjeton_droit=c;
    c->jeton.lexem=VARIABLE;
    //c->jeton.valeur.reel=2;
    Eval(a_test, tabX,*nb_valeur_ptr, tabY);
    return 0;
}

void myKey(int c)
{
    double deplacement = app.echelle*0.25;
    switch (c)
    {
    case 27 :  //touche esc pour quitter
        exit(0);
        break;
    case 'z':
        app.centre.y -= deplacement;
        break;
    case 's':
        app.centre.y += deplacement;
        break;
    case 'q':
        app.centre.x += deplacement;
        break;
    case 'd':
        app.centre.x -= deplacement;
        break;
    case 'p':
        app.echelle = app.echelle / 1.5;
        break;
    case 'm':
        app.echelle = app.echelle * 1.5;
        break;
    case 'f':
        run_once=0;
    case 'Z':
        app.centre.y -= deplacement;
        break;
    case 'S':
        app.centre.y += deplacement;
        break;
    case 'Q':
        app.centre.x += deplacement;
        break;
    case 'D':
        app.centre.x -= deplacement;
        break;
    case 'P':
        app.echelle = app.echelle / 1.5;
        break;
    case 'M':
        app.echelle = app.echelle * 1.5;
        break;
    case 'F':
        run_once=0;
    }
}

void myDraw(void)
{

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    logo_imt();
    setcolor(0.0F, 0.0F, 0.0F);
    axe(app);

    setcolor(0.8f, 0.8f, 0.8f);
//    affiche_graduation(app);

    cartesien p1, p2;

    if (run_once==0)
    {

        setup();
        run_once++;
    }

//      Liste *maListe = initialisation();
   // int tab[5]={0,1,2,3,4};

/*    for (int i=borne_inf;i<borne_sup;i+=pas){
      insertion(maListe,tabY[i]);
    }
    //for (i =borne_inf; i <borne_sup; i +=pas){
    //  if(tabY[i].lexem==ERREUR){

    //}
    //}
    */

    tabXfin = (double*) malloc(sizeof(double) * (*nb_valeur_ptr));
    tabYfin = (double*) malloc(sizeof(double) * (*nb_valeur_ptr));

    while(i < (*nb_valeur_ptr)){
        if(tabY[i].lexem==ERREUR){
            (*nb_valeur_ptr)--;
        }else{
            tabXfin[i]=tabX[i];
            tabYfin[i]=tabY[i].valeur.reel;
            i++;
        }
    }

    for (i =0; i < (*nb_valeur_ptr); i +=1)
    {
        p1.x = tabXfin[i];
        p1.y = tabYfin[i];

        p2.x = tabXfin[i+1];
        p2.y = tabYfin[i+1]; // Remplacer fonction par evalatueur + analyse token
        normalisation(p1, app, &p1);
        normalisation(p2, app, &p2);
        setcolor(0.0F, 1.0F, 0.0F);
        ligne(p1, p2);

    }

    for(int i=0; i<*nb_valeur_ptr; i++)
    {
        (tabY[i].lexem==ERREUR)? printf("marshpa\n") : printf("%lf\n",(tabY+i)->valeur.reel);
    }

}

int main(int ac, char *av[])

{

    printf("-------------------------------------------------\n");
    printf("|                                               |\n");
    printf("|              Guide de commande                |\n");
    printf("|                                               |\n");
    printf("|-----------------------------------------------|\n");
    printf("|                                               |\n");
    printf("|      - 'z' deplacement vers le haut           |\n");
    printf("|      - 'q' deplacement vers le bas            |\n");
    printf("|      - 's' deplacement vers la gauche         |\n");
    printf("|      - 'd' deplacement vers la droite         |\n");
    printf("|      - 'p' afin de zoomer                     |\n");
    printf("|      - 'm' afin de dezoomer                   |\n");
    printf("|      - 'esc' pour fermer la fenetre           |\n");
    printf("|      - 'f' pour changer les bornes et le pas  |\n");
    printf("-------------------------------------------------\n");

    app.centre.x = 0;
    app.centre.y = 0;
    app.echelle = 5;

    InitGraph(ac, av, "Essai Glut", 640, 480, myDraw, myKey);
    free(tabX);
    free(tabY);
    free(tabXfin);
    free(tabYfin);
    free(nb_valeur_ptr);

    return 0;
}

Body:
I bet on corruption rather that double free.

If we assume that Arbre is a pointer in Arbre plus=(Arbre)malloc(sizeof(Arbre)), the code allocates space for a pointer, but then uses it as a complete record:

plus->jeton.lexem=OPERATEUR;
plus->jeton.valeur.operateur=PLUS;
plus->pjeton_gauche=b;

This will inevitably overwrite additional memory and corrupt the heap. When later calling free, this corruption is detected.


问:
How can i solve a "Property 'style' does not exist on type 'Element' error?
I really need help to solve this error. I wrote the following JavaScript code below to enable my tab indicator to show on a clicked tab when clicked on but all I am getting is an error which says: "Property 'style' doesn't exist on type 'Element'". The tabs work perfectly fine, I can switch from one tab to the other. I have seen similar questions but my issue wasn't resolved following their lead suggestions. I am currently building an angular project and i wrote my JavaScript in the ngInit(){} function in my .ts file. The code is below:

```<code>ngOnInit() {
    let tabPanes = this._class('tab-header')[0].getElementsByTagName('div');

    for (let i = 0; i < tabPanes.length; i++) {
      tabPanes[i].addEventListener('click', () => {
        this._class('tab-header')[0]
          .getElementsByClassName('active')[0]
          .classList.remove('active');
          tabPanes[i].classList.add("active");

          this._class('tab-indicator')[0].style.top = 'calc(80px + ${i*50}px)'; // This flags a "property 'style' doe not exist on type 'Element'" error.

          this._class('tab-content')[0]
          .getElementsByClassName('active')[0]
          .classList.remove('active');

          this._class('tab-content')[0]
          .getElementsByTagName('div')[i]
          .classList.add('active');
      });
    }
  }

_class(name: any) {
    return document.getElementsByClassName(name);
  }
</code>```

Where did i go wrong? Any idea on how to solve this?

答:
getElementsByClassName returns an HTMLCollectionOf<Element> . There is no style property on Element type and hence the error.

You can type cast it to collection of HTMLElement and that should resolve the issue:

_class(name: any): HTMLCollectionOf<HTMLElement> {
    return document.getElementsByClassName(name) as HTMLCollectionOf<HTMLElement>;
}
```

PS: Though the above should resolve the typescript error, but as Eliseo mentioned in one of the comments, you can make use of Angular event binding and property binding to class attribute to do it Angular way.

Body:
I really need help to solve this error. I wrote the following JavaScript code below to enable my tab indicator to show on a clicked tab when clicked on but all I am getting is an error which says: "Property 'style' doesn't exist on type 'Element'". The tabs work perfectly fine, I can switch from one tab to the other. I have seen similar questions but my issue wasn't resolved following their lead suggestions. I am currently building an angular project and i wrote my JavaScript in the ngInit(){} function in my .ts file. The code is below:

ngOnInit() {
    let tabPanes = this._class('tab-header')[0].getElementsByTagName('div');

    for (let i = 0; i < tabPanes.length; i++) {
      tabPanes[i].addEventListener('click', () => {
        this._class('tab-header')[0]
          .getElementsByClassName('active')[0]
          .classList.remove('active');
          tabPanes[i].classList.add("active");

          this._class('tab-indicator')[0].style.top = 'calc(80px + ${i*50}px)'; // This flags a "property 'style' doe not exist on type 'Element'" error.

          this._class('tab-content')[0]
          .getElementsByClassName('active')[0]
          .classList.remove('active');

          this._class('tab-content')[0]
          .getElementsByTagName('div')[i]
          .classList.add('active');
      });
    }
  }

_class(name: any) {
    return document.getElementsByClassName(name);
  }

Where did i go wrong? Any idea on how to solve this?

Body:
getElementsByClassName returns an HTMLCollectionOf<Element> . There is no style property on Element type and hence the error.

You can type cast it to collection of HTMLElement and that should resolve the issue:

_class(name: any): HTMLCollectionOf<HTMLElement> {
    return document.getElementsByClassName(name) as HTMLCollectionOf<HTMLElement>;
}

PS: Though the above should resolve the typescript error, but as Eliseo mentioned in one of the comments, you can make use of Angular event binding and property binding to class attribute to do it Angular way.


问:
what props are used for in vuejs
I came across this snippet of code:

  props: {
    clicks: {
      type: Object,
      default: null,
    }
    events: {
      type: Object,
      default: null,
    },
  }```

I didn't understand from where props are retreived, from database ? or received from another component ?

答:
In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components.

This is specifically used to share data from its immediate parent to the child.

In youe case, your parent component template will be something like.

```<code><template>
    <div>
        <child-component-name :clicks="myClickObject" :events="myEventsObject">
        </child-component-name>
    </div>
</template>
</code>```

Where myClickObject and myEventsObject are objects defined in your immediate parent component from which child-component-name has been called.

Title: what props are used for in vuejs

Body:
I came across this snippet of code:

  props: {
    clicks: {
      type: Object,
      default: null,
    }
    events: {
      type: Object,
      default: null,
    },
  }

I didn't understand from where props are retreived, from database ? or received from another component ?

Body:
In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components.

This is specifically used to share data from its immediate parent to the child.

In youe case, your parent component template will be something like.

<template>
    <div>
        <child-component-name :clicks="myClickObject" :events="myEventsObject">
        </child-component-name>
    </div>
</template>

Where myClickObject and myEventsObject are objects defined in your immediate parent component from which child-component-name has been called.