问:
Im using putty for a class assignment and I am getting a segmentation fault
Write  a  C  program that counts  the number of  non  white-space  characters in  an input text file.  Program takes  as command argument(s)  the name of  the  input  file  (and the output  file  with option  -f). Based on the  option flags, it  displays the output  on the standard output, or writes  the output to an output  file.    (25 points)

The  command  format is as follows:

command     -f     inputfile    outputfile

or,

command     -s     inputfile

-f  indicates writing  to an  output  file;

-s  indicates displaying  the  output  on the screen.

I am receiving the segmentation fault on the -s command

```<code>#include <stdio.h>
#define BLANK ' '
#define NEWLINE '\n'

int main(int argc, char *argv[])
{
        FILE *infile;
        char c;
        int char_count=0;

        FILE *outfile;
        outfile = fopen(argv[3], "w");

        //checks for the argc length to be within the correct perameteres

        if ((argc < 3) || (argc > 4))
        {
                printf("Incorrect format, please try gain\n");
                exit(1);
        }

        //checks the input file to see if it is empty

        if ( (infile= fopen(argv[2], "r")) == NULL)
        {
                fprintf(stderr,"%s: cannot open %s \n", argv[0], argv[1]);
                exit(1);
        }

        // count the number of charecters in infile

        while ( (c = getc(infile)) != EOF)
                if ((c != BLANK) && (c != NEWLINE) )
                        char_count++;

        //checks to see if the command is -s or not, outputing the corrct message to the  desired location

        if (argv[1] == "-s")
        {
                printf("%d characters\n", char_count);
        }
        else
        {
                fprintf(outfile, "%s contains %d characters\n", argv[2],  char_count);
        }

        return 0;
}
</code>```

答:
```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BLANK ' '
#define NEWLINE '\n'

int main(int argc, char *argv[])
{
    FILE *infile;
    FILE *outfile;
        char c;
        int char_count=0;

        //checks for the argc length to be within the correct perameteres
        if ((argc < 3) || (argc > 4))
        {
                printf("Incorrect format, please try gain\n");
                exit(1);
        }

    //checks if passed second argument is valid (-f or -s)
    if (strcmp(argv[1], "-f") == 0) {
        if (argc < 4) {
            fprintf(stderr, "Please inform output file. Usage: -f inputfile outputfile");
            exit(1);
        }
        outfile = fopen(argv[3], "w");
    }
    else if (strcmp(argv[1], "-s") != 0) {
        fprintf(stderr, "Parameter not recognized: %s\n", argv[1]);
        exit(1);
    }

        //checks the input file to see if it is empty
        if ( (infile= fopen(argv[2], "r")) == NULL)
        {
                fprintf(stderr,"%s: cannot open %s \n", argv[0], argv[1]);
                exit(1);
        }

        // count the number of charecters in infile
        while ( (c = getc(infile)) != EOF)
                if ((c != BLANK) && (c != NEWLINE) )
                        char_count++;

        //checks to see if the command is -s or not, outputing the corrct message to the  desired location
        if (strcmp(argv[1], "-s") == 0)
        {
                printf("%d characters\n", char_count);
        }
        else
        {
                fprintf(outfile, "%s contains %d characters\n", argv[2],  char_count);
        printf("Result written to %s\n", argv[3]);
        }

        return 0;
}
</code>```

Body:
Write  a  C  program that counts  the number of  non  white-space  characters in  an input text file.  Program takes  as command argument(s)  the name of  the  input  file  (and the output  file  with option  -f). Based on the  option flags, it  displays the output  on the standard output, or writes  the output to an output  file.    (25 points)

The  command  format is as follows:

command     -f     inputfile    outputfile

or,

command     -s     inputfile

-f  indicates writing  to an  output  file;

-s  indicates displaying  the  output  on the screen.

I am receiving the segmentation fault on the -s command

#include <stdio.h>
#define BLANK ' '
#define NEWLINE '\n'

int main(int argc, char *argv[])
{
        FILE *infile;
        char c;
        int char_count=0;

        FILE *outfile;
        outfile = fopen(argv[3], "w");

        //checks for the argc length to be within the correct perameteres

        if ((argc < 3) || (argc > 4))
        {
                printf("Incorrect format, please try gain\n");
                exit(1);
        }

        //checks the input file to see if it is empty

        if ( (infile= fopen(argv[2], "r")) == NULL)
        {
                fprintf(stderr,"%s: cannot open %s \n", argv[0], argv[1]);
                exit(1);
        }

        // count the number of charecters in infile

        while ( (c = getc(infile)) != EOF)
                if ((c != BLANK) && (c != NEWLINE) )
                        char_count++;

        //checks to see if the command is -s or not, outputing the corrct message to the  desired location

        if (argv[1] == "-s")
        {
                printf("%d characters\n", char_count);
        }
        else
        {
                fprintf(outfile, "%s contains %d characters\n", argv[2],  char_count);
        }

        return 0;
}


来源: stackexchange

问:
How to install Solana on Windows?
I ran:

curl https://release.solana.com/v1.8.3/solana-install-init-x86_64-pc-windows-msvc.exe --output C:\solana-install-tmp\solana-install-init.exe --create-dirs

In my Windows command prompt and it showed up like this:

It seemed like it installed - so then I did solana --version and this is what happened:

'solana' is not recognized as an internal or external command, operable program or batch file.

I ran solana --version in Powershell, Git Bash, VS Code Terminal, and Command Prompt and it gives the same output.

How do I install Solana?

Thank you!

答:
You did step 1 of 2 to install Solana - right now you have the directory of files copied,

Run C:\solana-install-tmp\solana-install-init.exe v1.8.3 to actually install. Then make sure that either PATH is auto-updated or copy the generated PATH and update it manually.

CLOSE the CMD right after and relaunch. THEN try Solana --version.

ContentLicense: CC BY-SA 4.0

Title: How to install Solana on Windows?


问:
Email validation Method creation
The method  returns true if such    character

is  a   letter  of  the English alphabet    (uppercase  or  lower   case)   or  one of  the arabic  numerals.   The method
returns false otherwise

答:
Method for ASCII character set</p>
```<code>boolean isEnglishLetterOrDigit(char letter) {
      return (letter >= 'a' && letter <= 'z') ||
             (letter >= 'A' && letter <= 'Z') ||
             (letter >= '0' && letter <= '9');
  }
</code>```

Title: Email validation Method creation

Body:
Method for ASCII character set

boolean isEnglishLetterOrDigit(char letter) {
      return (letter >= 'a' && letter <= 'z') ||
             (letter >= 'A' && letter <= 'Z') ||
             (letter >= '0' && letter <= '9');
  }


问:
Download values of list from json file
I have simple class

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public List<string> ParentsNames { get; set; }
}
```
<p>And a json file</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "Name": "Frank",
    "Surname": "Wilson",
    "Age": "52",
    "Login": "fwillock",
    "Password": "willock123",
    "ParentsNames": [
      "Charles",
      "Sarah"
    ]
  },
  {
    "Name": "Karen",
    "Surname": "Davies",
    "Age": "35",
    "Login": "kdavies",
    "Password": "davies123",
    "ParentsNames": [
      "Jason",
      "Angela"
    ]
  }
]
</code>```

I need to get in console all names or surnames, existing in Person list. I tried to use something like this:

var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());
```

But i don't have any idea to use it in my code.
Thanks in advance.

答:
list of names

```<code>var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
</code>```

to print

```<code>foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");
</code>```

Title: Download values of list from json file

Body:
I have simple class

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public List<string> ParentsNames { get; set; }
}

And a json file

[
  {
    "Name": "Frank",
    "Surname": "Wilson",
    "Age": "52",
    "Login": "fwillock",
    "Password": "willock123",
    "ParentsNames": [
      "Charles",
      "Sarah"
    ]
  },
  {
    "Name": "Karen",
    "Surname": "Davies",
    "Age": "35",
    "Login": "kdavies",
    "Password": "davies123",
    "ParentsNames": [
      "Jason",
      "Angela"
    ]
  }
]

I need to get in console all names or surnames, existing in Person list. I tried to use something like this:

var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());

But i don't have any idea to use it in my code.
Thanks in advance.

Body:
list of names

var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();

to print

foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");


问:
How to find a name with the fourth highest score?
pardon this silly question but I need your help.

I have a list of name, let's say

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']

and their scores are

score = [75,60,80,79,90,30]

How to write the code in Python so if I want to know the fourth highest score the result is

The fourth highest score is Alpha.

Thanks in advance for your help.

答:
An alternative answer is to use a dictionary. A dictionary is better than two lists because it only uses one variable, and scores are tied to their name so you don't have to maintain matching indexes. This answer is assuming you are using python 3.7 or newer.sorted_scores contains  sorted list of tuples structured (name,points).

```<code>scores = {
    "Alpha" : 75,
    "Betta" : 60,
    "Chroma" : 80,
    "Delta" : 79,
    "Echo" : 90,
    "Froyo" : 50
}
sorted_scores = sorted(scores.items(),key=lambda item: item[1])
print(f"The fourth highest score is {sorted_scores[-4][0]} with {sorted_scores[-4][1]} points.")
#reason for -4 is that sorted() returns the list lowest to highest, and -4 is the fourth from the end. To have higher scores at the top, add reverse=True as a parameter of sorted() and replace -4 with 3.
</code>```

Body:
An alternative answer is to use a dictionary. A dictionary is better than two lists because it only uses one variable, and scores are tied to their name so you don't have to maintain matching indexes. This answer is assuming you are using python 3.7 or newer.sorted_scores contains  sorted list of tuples structured (name,points).

scores = {
    "Alpha" : 75,
    "Betta" : 60,
    "Chroma" : 80,
    "Delta" : 79,
    "Echo" : 90,
    "Froyo" : 50
}
sorted_scores = sorted(scores.items(),key=lambda item: item[1])
print(f"The fourth highest score is {sorted_scores[-4][0]} with {sorted_scores[-4][1]} points.")
#reason for -4 is that sorted() returns the list lowest to highest, and -4 is the fourth from the end. To have higher scores at the top, add reverse=True as a parameter of sorted() and replace -4 with 3.


问:
How to assign values to dynamic const variable in C?
I got curious about dynamic const variable in C.

So, when I was testing there is a problem with assigning a value to it, while there is no problem with allocating const variable dynamically.

Yeah I am aware that we can use static const variables but it will be more memory efficient if we want to work with big const struct.

so here is a program that I had tested..

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    const int *a = (int*) malloc(sizeof(int));
    *a = 77;
    printf("value of a %d", a);
    return 0;
}
</code>```

The error I am getting..

```<code>main.c:15:8: error: assignment of read-only location ‘*a’
   15 |     *a = 15;
      |        ^
</code>```

So is there any way to do it?

答:
The purpose of const is largely to help programmers avoid modifying an object unintentionally. When you declare a with const int *a, then the type of *a is const int. In particular, it is const qualified, and this means it is not modifiable per C 2018 6.3.2.1 1:

… A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type,…

Using *a as the left operand of an assignment violates C 2018 6.5.16 2:

An assignment operator shall have a modifiable lvalue as its left operand.

Essentially, declaring a with const int *a says you do not want to modify *a.

If you want to dynamically allocate memory, assign it an initial value, and then use it as a const type, you can do this with two pointers:

```<code>int *p = malloc(sizeof *p);
if (!p)
{
    fprintf(stderr, "Error, unable to allocate memory.\n");
    exit(EXIT_FAILURE);
}
*p = 77;
const int *a = p;
</code>```

Then *p is a modifiable lvalue you can use to change the memory, and *a is a non-modifiable lvalue you could pass to another routine with the const qualifier to help avoid inadvertent changes to the memory. (It is not an absolute guarantee; the C standard allows code to convert a const int * to an int * and use it to modify the memory, as long as it does not point to an object that was originally defined with const.)

You could further reduce the opportunity for accidentally modifying the memory by reducing the scope of p:

```<code>const int *a;
{
    int *p = malloc(sizeof *p);
    if (!p)
    {
        fprintf(stderr, "Error, unable to allocate memory.\n");
        exit(EXIT_FAILURE);
    }
    *p = 77;
    a = p;
}
// p is not in scope here, but a is.
printf("*a = %d.\n", *a);
</code>```

However, then, when you pass the address to free, you need to use a cast to remove const, as in free((void *) a);.

Body:
I got curious about dynamic const variable in C.

So, when I was testing there is a problem with assigning a value to it, while there is no problem with allocating const variable dynamically.

Yeah I am aware that we can use static const variables but it will be more memory efficient if we want to work with big const struct.

so here is a program that I had tested..

#include <stdio.h>
#include <stdlib.h>

int main()
{
    const int *a = (int*) malloc(sizeof(int));
    *a = 77;
    printf("value of a %d", a);
    return 0;
}

The error I am getting..

main.c:15:8: error: assignment of read-only location ‘*a’
   15 |     *a = 15;
      |        ^

So is there any way to do it?

Body:
The purpose of const is largely to help programmers avoid modifying an object unintentionally. When you declare a with const int *a, then the type of *a is const int. In particular, it is const qualified, and this means it is not modifiable per C 2018 6.3.2.1 1:

… A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type,…

Using *a as the left operand of an assignment violates C 2018 6.5.16 2:

An assignment operator shall have a modifiable lvalue as its left operand.

Essentially, declaring a with const int *a says you do not want to modify *a.

If you want to dynamically allocate memory, assign it an initial value, and then use it as a const type, you can do this with two pointers:

int *p = malloc(sizeof *p);
if (!p)
{
    fprintf(stderr, "Error, unable to allocate memory.\n");
    exit(EXIT_FAILURE);
}
*p = 77;
const int *a = p;

Then *p is a modifiable lvalue you can use to change the memory, and *a is a non-modifiable lvalue you could pass to another routine with the const qualifier to help avoid inadvertent changes to the memory. (It is not an absolute guarantee; the C standard allows code to convert a const int * to an int * and use it to modify the memory, as long as it does not point to an object that was originally defined with const.)

You could further reduce the opportunity for accidentally modifying the memory by reducing the scope of p:

const int *a;
{
    int *p = malloc(sizeof *p);
    if (!p)
    {
        fprintf(stderr, "Error, unable to allocate memory.\n");
        exit(EXIT_FAILURE);
    }
    *p = 77;
    a = p;
}
// p is not in scope here, but a is.
printf("*a = %d.\n", *a);

However, then, when you pass the address to free, you need to use a cast to remove const, as in free((void *) a);.


问:
C Python How to create a function inside another function as a decorator using C
I would like to know how to create a Python function inside another Python function using C?
Try something like this:

static PyObject *func(PyObject *self, PyObject *wrap) { // METH_O
       PyObject *newfunc(PyObject *self, PyObject *args, PyObject *kwds) = { return PyObject_Call(wrap, args, kwds); }
       return newfunc;
}
```

But the compiler expects another expression. I would like to know (or some clues) to advance my project, How to create a function inside another python function using C?

答:
C does not have closures. You cannot create a C function inside another C function and give it access to local variables from the function that defined it. Even if you could, the new C function would not be directly usable as a Python function.

You can write Python classes in the Python C API, and this is the usual way to write Python decorators in C. For example, instead of writing

```<code>def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper
</code>```

a decorator written in C would look more like the C API equivalent of

```<code>class decorator:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)
</code>```

A full, detailed guide on how to create Python classes in C would be beyond the scope of this answer. See the previously linked documentation for a tutorial, and note that the C-level hook for __call__ is the tp_call slot.

You can look at the C implementation of functools.partial for an example, either the old 3.6 implementation for a simple example or a more recent version if you want to get fancy with the new vectorcall mechanism.

Body:
I would like to know how to create a Python function inside another Python function using C?
Try something like this:

static PyObject *func(PyObject *self, PyObject *wrap) { // METH_O
       PyObject *newfunc(PyObject *self, PyObject *args, PyObject *kwds) = { return PyObject_Call(wrap, args, kwds); }
       return newfunc;
}

But the compiler expects another expression. I would like to know (or some clues) to advance my project, How to create a function inside another python function using C?

Body:
C does not have closures. You cannot create a C function inside another C function and give it access to local variables from the function that defined it. Even if you could, the new C function would not be directly usable as a Python function.

You can write Python classes in the Python C API, and this is the usual way to write Python decorators in C. For example, instead of writing

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

a decorator written in C would look more like the C API equivalent of

class decorator:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

A full, detailed guide on how to create Python classes in C would be beyond the scope of this answer. See the previously linked documentation for a tutorial, and note that the C-level hook for __call__ is the tp_call slot.

You can look at the C implementation of functools.partial for an example, either the old 3.6 implementation for a simple example or a more recent version if you want to get fancy with the new vectorcall mechanism.


问:
How to open an App from a link in email?
I have to open my App from a link in email .that is when registering in my App,i got a mail contains a link something like: click for open your app.so when i click the link from my mobile browser i need  the app  Launched.Is there any solution for this?

答:
This is not possible.

Just include instructions to open the app in the email if need be.

ContentLicense: CC BY-SA 3.0


问:
Receiving error when I try to start a Scrapy project
I'm trying to start a new project using Scrapy on MAC OS, and after creating a new conda environment and installing scrapy, I can't get the startproject function to work.

In my environment, I run...

```<code>scrapy startproject scraper
</code>```

Then, I receive this traceback.

```<code>Traceback (most recent call last):
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/scrapy", line 5, in <module>
    from scrapy.cmdline import execute
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/cmdline.py", line 9, in <module>
    from scrapy.crawler import CrawlerProcess
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/crawler.py", line 18, in <module>
    from scrapy.core.engine import ExecutionEngine
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/core/engine.py", line 14, in <module>
    from scrapy.core.scraper import Scraper
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/core/scraper.py", line 16, in <module>
    from scrapy.utils.log import failure_to_exc_info, logformatter_adapter
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/log.py", line 12, in <module>
    from scrapy.utils.versions import scrapy_components_versions
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/versions.py", line 12, in <module>
    from scrapy.utils.ssl import get_openssl_version
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/ssl.py", line 1, in <module>
    import OpenSSL
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/crypto.py", line 11, in <module>
    from OpenSSL._util import (
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/_util.py", line 5, in <module>
    from cryptography.hazmat.bindings.openssl.binding import Binding
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module>
    from cryptography.hazmat.bindings._openssl import ffi, lib
ImportError: dlopen(/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
  Referenced from: /Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so
  Reason: tried: '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/../../libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/../../libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/../lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)
</code>```

I'm not quite sure what I'm looking at with this error, and my searching on Google/Stackoverflow has been to no avail. Any idea why I can't start a new scrapy project in my environment?

答:
your os is Mac, I think, try those commands:</p>
```<code>brew update
brew upgrade
brew cleanup
</code>```

Body:
I'm trying to start a new project using Scrapy on MAC OS, and after creating a new conda environment and installing scrapy, I can't get the startproject function to work.

In my environment, I run...

scrapy startproject scraper

Then, I receive this traceback.

Traceback (most recent call last):
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/scrapy", line 5, in <module>
    from scrapy.cmdline import execute
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/cmdline.py", line 9, in <module>
    from scrapy.crawler import CrawlerProcess
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/crawler.py", line 18, in <module>
    from scrapy.core.engine import ExecutionEngine
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/core/engine.py", line 14, in <module>
    from scrapy.core.scraper import Scraper
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/core/scraper.py", line 16, in <module>
    from scrapy.utils.log import failure_to_exc_info, logformatter_adapter
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/log.py", line 12, in <module>
    from scrapy.utils.versions import scrapy_components_versions
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/versions.py", line 12, in <module>
    from scrapy.utils.ssl import get_openssl_version
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/scrapy/utils/ssl.py", line 1, in <module>
    import OpenSSL
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/crypto.py", line 11, in <module>
    from OpenSSL._util import (
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/OpenSSL/_util.py", line 5, in <module>
    from cryptography.hazmat.bindings.openssl.binding import Binding
  File "/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module>
    from cryptography.hazmat.bindings._openssl import ffi, lib
ImportError: dlopen(/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
  Referenced from: /Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so
  Reason: tried: '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/../../libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/lib/python3.8/site-packages/../../libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/../lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/opt/concourse/worker/volumes/live/903ea60a-0489-485f-6f93-162648469061/volume/python_1573076474316/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/lib/libffi.7.dylib' (no such file), '/Users/alexmcgraw/opt/anaconda3/envs/espn_daily_sport_env/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)

I'm not quite sure what I'm looking at with this error, and my searching on Google/Stackoverflow has been to no avail. Any idea why I can't start a new scrapy project in my environment?

Body:
your os is Mac, I think, try those commands:

brew update
brew upgrade
brew cleanup


问:
Possible to get 'regex source' from match?
I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*```
</div>
</div>
</p>
<p>Or:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let r2 = /el*/;
console.log(r2.source);
// el*</code>```

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

```<code>let m = "Hello".match(/el*/);
console.log(m.source?);
</code>```

答:
The match result by itself cannot lead to the original regex, simply because different regexes can lead to the same result, even on the same string. Take for example the string "abcd" - all the following regexes: /abcd/, /a..d/ /a.*/ and many more, would match the string exactly the same way.

The only way you could retrive the original regex is if a reference to the regex was literally stored by the match() method inside the returned object. There is no reason to think that's the case, but you can implement your own match function that would do. Something like

```<code>function myMatch(str, regex) {
  var match = str.match(regex);
  if (match === null) {
    match = [null];
  }
  match.source = regex;
  return match;
}
</code>```

Body:
I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);
// el*

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);

Body:
The match result by itself cannot lead to the original regex, simply because different regexes can lead to the same result, even on the same string. Take for example the string "abcd" - all the following regexes: /abcd/, /a..d/ /a.*/ and many more, would match the string exactly the same way.

The only way you could retrive the original regex is if a reference to the regex was literally stored by the match() method inside the returned object. There is no reason to think that's the case, but you can implement your own match function that would do. Something like

function myMatch(str, regex) {
  var match = str.match(regex);
  if (match === null) {
    match = [null];
  }
  match.source = regex;
  return match;
}


问:
Error creating BackendService: googleapi: Error 403: Required 'compute.backendServices.create' permission for 'projects/myproject-137813/global/backen
On GCP, I'm trying to create a Backend Service with this Terraform code below:

resource "google_compute_backend_service" "default" {
  name      = "backend-service"

  backend {
    group = google_compute_region_network_endpoint_group.cloudrun_neg.id
  }
}
```

But I got this error below:

Error creating BackendService: googleapi: Error 403: Required
'compute.backendServices.create' permission for
'projects/myproject-137813/global/backendServices/backend-service',
forbidden

So now, I'm trying to add a role to solve this error above but there are too many roles to choose:

What role do I need to choose?

答:
You need to choose the role "Compute Network Admin" to create a Backend Service:

In addition, you can choose the more abstract role "Compute Admin" to create a Backend Service:

Body:
On GCP, I'm trying to create a Backend Service with this Terraform code below:

resource "google_compute_backend_service" "default" {
  name      = "backend-service"

  backend {
    group = google_compute_region_network_endpoint_group.cloudrun_neg.id
  }
}

But I got this error below:

Error creating BackendService: googleapi: Error 403: Required
'compute.backendServices.create' permission for
'projects/myproject-137813/global/backendServices/backend-service',
forbidden

So now, I'm trying to add a role to solve this error above but there are too many roles to choose:

What role do I need to choose?


问:
Snakefile how to mix wildcards and variables
I want to make a rule which for a given number of threads translates files in one directory and format to another directory and format, in parallel.  Certain elements of the path are defined by variables and certain are wildcards. I want it to wildcard on phase and sample and ext but take stage, challenge and language from the Python variable environment.   I want the copy operation to take file to file. I don't want it to get the entire list of files as input.  I'm not using expand here because if I use expand then snakemake will pass the entire list of inputs as {input} and the entire list of outputs as {output} to the function, which is not what I want.  Here is the Snakefile:

```<code>from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

stage = "/media/catskills/interspeech22"
challenge = "openasr21"
language = "farsi"
sample_rate = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         "{stage}/{challenge}_{language}/{phase}/audio/{sample}.{ext}"
     output:
         "{stage}/{challenge}_{language}/{phase}/wav_{sample_rate}/{sample}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

When I run it I get this error:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'
</code>```

Is there a way to do this in snakemake?

UPDATE: I found a partial solution here, which is to use f-strings and double curly quote the patterns.

```<code>from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/audio/{{sample}}.{{ext}}"
     output:
     f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/wav_{{SAMPLE_RATE}}/{{sample}}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However the wildcard is not matching the subdirectory name.  I'm still getting an error, but it's a little different:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'phase'
</code>```

This leads to here:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.wav" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However I'm still not done yet:

```<code>$ snakemake -c16
Building DAG of jobs...
WorkflowError:
Target rules may not contain wildcards. Please specify concrete files or a rule without wildcards at the command line, or have a rule without wildcards at the very top of your workflow (e.g. the typical "rule all" which just collects all results you want to generate in the end).
</code>```

I add rule all in an attempt to correct this issue:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

sph_results = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
               for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
        sph_results

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.sph" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

Finally it complains that the files to be constructed don't exist yet, before attempting to call this function which will construct them:

```<code>$ snakemake -c16
Building DAG of jobs...
MissingInputException in line 15 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Missing input files for rule all:
/media/catskills/interspeech22/openasr21_farsi/dev/wav_16000/MATERIAL_OP2-3S-BUILD_46645_20171106_064534_inLine.wav
/media/catskills/interspeech22/openasr21_farsi/eval/wav_16000/MATERIAL_OP2-3S_77793199_outLine.wav
</code>```

where, to fill out the example, the function copy_sph_to_wav is:

```<code>import os
import librosa
import soundfile as sf

def copy_sph_to_wav(src, dst, sr):
    cmd='/home/catskills/is22/sph2pipe_v2.5/sph2pipe'
    if src[-4:]=='.wav':
        audio,sr1=librosa.load(src, sr=sr)
    else:
        os.system(f"{cmd} -f wav {src} {dst}")
        audio,sr1=librosa.load(dst, sr=sr)

    sf.write(dst, audio, sr)
</code>```

UPDATE 2: Which leads us here, where we fix some issues with the sph_to_wav rule generating outputs which do not match our OUTPUTS file:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/audio/{sample}.{ext}'
     output:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/wav_16000/{sample}.wav'
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However we still get an error but a much more focused one, which is:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'
</code>```0

There may be a clue here having to do with wildcard_constraints.

UPDATE 3:  This answer says that

Each wildcard in the input section shall have a corresponding wildcard
(with the same name) in the output section. That is how Snakemake
works: when the Snakemake tries to constract the DAG of jobs and finds
that it needs a certain file, it looks at the output section for each
rule and checks if this rule can produce the required file. This is
the way how Snakemake assigns certain values to the wildcard in the
output section. Every wildcard in other sections shall match one of
the wildcards in the output, and that is how the input gets concrete
filenames.

If that is true then I don't think there is a snakemake solution because I am trying to replace the .sph with .wav and I don't want to have to make a .sph.wav file.

答:
I finally got it. Not 100% happy about it (would rather have had .{ext} in the input but not the output), but this works and I guess it makes it's own kind of sense.  The issue being that my input directory can have either .sph or .wav files depending on the vagaries of the data provider, so I have to be ready for either contingency:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav
from copy_wav_to_wav import copy_wav_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.sph" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / f"{{phase}}/wav_{SAMPLE_RATE}/{{sample}}.wav" )
     run:
         copy_sph_to_wav(list({input})[0][0], list({output})[0][0], SAMPLE_RATE)

rule wav_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.wav" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / f"{{phase}}/wav_{SAMPLE_RATE}/{{sample}}.wav" )
     run:
         copy_wav_to_wav(list({input})[0][0], list({output})[0][0], SAMPLE_RATE)
</code>```

Also I discovered by commenting my function that {input} is a set of a list with one element:

```<code>SRC {['/media/catskills/interspeech22/openasr21_farsi/build/audio/MATERIAL_OP2-3S-BUILD_29884_20170907_021506_outLine.sph']}
DST {['/media/catskills/interspeech22/openasr21_farsi/build/wav_16000/MATERIAL_OP2-3S-BUILD_29884_20170907_021506_outLine.wav']}
SR 16000
</code>```

which I didn't even know was possible, so I have to do this ugly conversion list({input})[0], I don't know exactly why.

In any event finally the consummation devoutly to be wished, for snakemake -c16:

Body:
I want to make a rule which for a given number of threads translates files in one directory and format to another directory and format, in parallel.  Certain elements of the path are defined by variables and certain are wildcards. I want it to wildcard on phase and sample and ext but take stage, challenge and language from the Python variable environment.   I want the copy operation to take file to file. I don't want it to get the entire list of files as input.  I'm not using expand here because if I use expand then snakemake will pass the entire list of inputs as {input} and the entire list of outputs as {output} to the function, which is not what I want.  Here is the Snakefile:

from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

stage = "/media/catskills/interspeech22"
challenge = "openasr21"
language = "farsi"
sample_rate = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         "{stage}/{challenge}_{language}/{phase}/audio/{sample}.{ext}"
     output:
         "{stage}/{challenge}_{language}/{phase}/wav_{sample_rate}/{sample}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

When I run it I get this error:

$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'

Is there a way to do this in snakemake?

UPDATE: I found a partial solution here, which is to use f-strings and double curly quote the patterns.

from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/audio/{{sample}}.{{ext}}"
     output:
     f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/wav_{{SAMPLE_RATE}}/{{sample}}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However the wildcard is not matching the subdirectory name.  I'm still getting an error, but it's a little different:

$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'phase'

This leads to here:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.wav" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However I'm still not done yet:

$ snakemake -c16
Building DAG of jobs...
WorkflowError:
Target rules may not contain wildcards. Please specify concrete files or a rule without wildcards at the command line, or have a rule without wildcards at the very top of your workflow (e.g. the typical "rule all" which just collects all results you want to generate in the end).

I add rule all in an attempt to correct this issue:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

sph_results = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
               for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
        sph_results

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.sph" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

Finally it complains that the files to be constructed don't exist yet, before attempting to call this function which will construct them:

$ snakemake -c16
Building DAG of jobs...
MissingInputException in line 15 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Missing input files for rule all:
/media/catskills/interspeech22/openasr21_farsi/dev/wav_16000/MATERIAL_OP2-3S-BUILD_46645_20171106_064534_inLine.wav
/media/catskills/interspeech22/openasr21_farsi/eval/wav_16000/MATERIAL_OP2-3S_77793199_outLine.wav

where, to fill out the example, the function copy_sph_to_wav is:

import os
import librosa
import soundfile as sf

def copy_sph_to_wav(src, dst, sr):
    cmd='/home/catskills/is22/sph2pipe_v2.5/sph2pipe'
    if src[-4:]=='.wav':
        audio,sr1=librosa.load(src, sr=sr)
    else:
        os.system(f"{cmd} -f wav {src} {dst}")
        audio,sr1=librosa.load(dst, sr=sr)

    sf.write(dst, audio, sr)

UPDATE 2: Which leads us here, where we fix some issues with the sph_to_wav rule generating outputs which do not match our OUTPUTS file:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/audio/{sample}.{ext}'
     output:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/wav_16000/{sample}.wav'
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However we still get an error but a much more focused one, which is:

$ snakemake -c16 -p -n
Building DAG of jobs...
WildcardError in line 19 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'ext'

There may be a clue here having to do with wildcard_constraints.

UPDATE 3:  This answer says that

Each wildcard in the input section shall have a corresponding wildcard
(with the same name) in the output section. That is how Snakemake
works: when the Snakemake tries to constract the DAG of jobs and finds
that it needs a certain file, it looks at the output section for each
rule and checks if this rule can produce the required file. This is
the way how Snakemake assigns certain values to the wildcard in the
output section. Every wildcard in other sections shall match one of
the wildcards in the output, and that is how the input gets concrete
filenames.

If that is true then I don't think there is a snakemake solution because I am trying to replace the .sph with .wav and I don't want to have to make a .sph.wav file.

Body:
I finally got it. Not 100% happy about it (would rather have had .{ext} in the input but not the output), but this works and I guess it makes it's own kind of sense.  The issue being that my input directory can have either .sph or .wav files depending on the vagaries of the data provider, so I have to be ready for either contingency:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav
from copy_wav_to_wav import copy_wav_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.sph" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / f"{{phase}}/wav_{SAMPLE_RATE}/{{sample}}.wav" )
     run:
         copy_sph_to_wav(list({input})[0][0], list({output})[0][0], SAMPLE_RATE)

rule wav_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.wav" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / f"{{phase}}/wav_{SAMPLE_RATE}/{{sample}}.wav" )
     run:
         copy_wav_to_wav(list({input})[0][0], list({output})[0][0], SAMPLE_RATE)

Also I discovered by commenting my function that {input} is a set of a list with one element:

SRC {['/media/catskills/interspeech22/openasr21_farsi/build/audio/MATERIAL_OP2-3S-BUILD_29884_20170907_021506_outLine.sph']}
DST {['/media/catskills/interspeech22/openasr21_farsi/build/wav_16000/MATERIAL_OP2-3S-BUILD_29884_20170907_021506_outLine.wav']}
SR 16000

which I didn't even know was possible, so I have to do this ugly conversion list({input})[0], I don't know exactly why.

In any event finally the consummation devoutly to be wished, for snakemake -c16:


问:
nodejs variable undefined when exporting
Hey I was wondering why the following returns undefined:

```<code>let variable;

module.exports.initialize = () => {
  variable = "123";
};

module.exports.variable = variable;

</code>```

I simply require the module in file A and then call the initialize function. In file B I require it and console.log the variable but it returns undefined. What am I missing here?

答:
module.exports.variable is a property on the module.exports object.  When you initialize your module, you assign the value of variable to that module.exports.variable property and that value is undefined at the time you assign it (because the initialize() function has not yet been called).

So, when your module is done initializing itself, module.exports.variable is undefined.

Then, sometime later someone else calls module.exports.initialize() and that changes the local variable within your module to "123".  That does not affect the value of the module.exports.variable property at all.  It remains undefined.

In the future, please don't give either a property or a variable the name variable as it makes it very difficult to document or discuss.  A different name that doesn't conflict with the English definition of the word variable would simplify discussing this code.

What you can do instead is export an object instead of a plain value.

```<code>let myObj = { name: "John"};

module.exports.setName = (name) => {
  myObj.name = name;
};

module.exports.sharedObj = myObj;
</code>```

Then, why you import it somewhere else

```<code>const aModule = require('./otherModule');
console.log(aModule.sharedObj);         // {name: "John"}

aModule.setName("Bob");
console.log(aModule.sharedObj);         // {name: "Bob"}
</code>```

Because objects in Javascript are assigned by pointer, when you did module.exports.sharedObj = myObj; in the module initialization, it put a pointer to myObj into module.exports.sharedObj so when myObj changes, anyone viewing module.exports.sharedObj will see that change too.  This only works this way for objects in Javascript, not for other types of values (strings, numbers, etc...).

Body:
Hey I was wondering why the following returns undefined:

let variable;

module.exports.initialize = () => {
  variable = "123";
};

module.exports.variable = variable;

I simply require the module in file A and then call the initialize function. In file B I require it and console.log the variable but it returns undefined. What am I missing here?

Body:
module.exports.variable is a property on the module.exports object.  When you initialize your module, you assign the value of variable to that module.exports.variable property and that value is undefined at the time you assign it (because the initialize() function has not yet been called).

So, when your module is done initializing itself, module.exports.variable is undefined.

Then, sometime later someone else calls module.exports.initialize() and that changes the local variable within your module to "123".  That does not affect the value of the module.exports.variable property at all.  It remains undefined.

In the future, please don't give either a property or a variable the name variable as it makes it very difficult to document or discuss.  A different name that doesn't conflict with the English definition of the word variable would simplify discussing this code.

What you can do instead is export an object instead of a plain value.

let myObj = { name: "John"};

module.exports.setName = (name) => {
  myObj.name = name;
};

module.exports.sharedObj = myObj;

Then, why you import it somewhere else

const aModule = require('./otherModule');
console.log(aModule.sharedObj);         // {name: "John"}

aModule.setName("Bob");
console.log(aModule.sharedObj);         // {name: "Bob"}

Because objects in Javascript are assigned by pointer, when you did module.exports.sharedObj = myObj; in the module initialization, it put a pointer to myObj into module.exports.sharedObj so when myObj changes, anyone viewing module.exports.sharedObj will see that change too.  This only works this way for objects in Javascript, not for other types of values (strings, numbers, etc...).


问:
CSS problem, 100% width keeps moving out of position
I'm currently working on this website,
http://no-illusions.nl
It's going fine but I found a pretty stupid thing that I can't resolve.

I have an div (wrapper) with an width of 500px and inside I have different div's containing images and text. Now the problem is that the text is dynamic in width, on some parts it could be 200px width and on some pages it could be 350px.

So I put the width on 100% but now the part just floats underneath where I want it!

This is how it should look,
![how it should look][1]

But this is how it looks,

I hope you guys can give me a push in the right direction.

答:
```<code>.update_respond p{width: 273px;}
</code>```

Body: .update_respond p{width: 273px;}


问:
Variable coming back null after just being set properly - Flutter
No matter what I do, my variable _authorizedUser is coming back null.

I'm demoing biometric authentication for users, once user enters their username, if it matches one in the local database and biometric auth is a success, then user will automatically be logged in. This is currently hardcoded for username and password...

I can't get this to work in any configuration, there must be something wrong I haven't discovered. No matter what I do authorizedUser comes back null, even after confirming with log that it IS NOT NULL. Somehow it is bouncing back to null & I am getting null error. Previously I had _authorizedUser as a late variable but that was even worse. I think this may be an issue for Github but I wanted to make sure first.

Weirdly enough, if I login the old fashioned way entering username & password with button press, calling the same login method it works as intended. But as soon as I call login from inside my biometric authentication method, it's a no go. Am I using Either wrong or something? Any help greatly appreciated :)

```<code>enum NotifierState { initial, loading, loaded }

class AuthenticationEndpoints extends ChangeNotifier {
  // Authorized user
  ParseUser? _authorizedUser;
  ParseUser? get authorizedUser => _authorizedUser;
  Future<void> _setAuthorizedUser(ParseUser? user) async {
    _authorizedUser = user;
    log(_authorizedUser.toString());                      /// This logs proper object...
    notifyListeners();
  }

  /// Login user
  ///
  /// returns either Failure or Success
  /// Failure => [DialogError]
  /// Success => [_authorizedUser] = [user] & Navigate [HomeScreen]
  Future<void> login(BuildContext context, String username, String password) async {
    Either<Failure, ParseUser> user = await AuthenticationServices.login(username, password);
    user.fold(
      (failure) {
        showDialog(context: context, builder: (context) => DialogError(failure: Failure(failure.message)));
      },
      (user) {                        /// Correctly returns user object from server
        _setAuthorizedUser(user);
        Get.to(const HomeScreen());
      },
    );
  }

  /// Biometric authentication
  ///
  /// returns either Failure or true
  /// Failure => [DialogError]
  /// bool => [true] (authentication successful)
  Future<void> biometricAuthentication(BuildContext context) async {
    Either<Failure, bool> biometricAuthenticationAttempt =
        await AuthenticationServices.biometricAuthentication();
    biometricAuthenticationAttempt.fold(
      (failure) =>
          showDialog(context: context, builder: (context) => DialogError(failure: Failure(failure.message))),
      (authenticated) async {
        await login(context, '0010', '0010');
      },
    );
  }

...

}

</code>```

Widget using variable

```<code>
final authenticationEndpoints = ChangeNotifierProvider((ref) => AuthenticationEndpoints());

class Welcome extends ConsumerWidget {
  const Welcome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    String? user = ref.watch(authenticationEndpoints).authorizedUser?.username;
    log(user.toString());                     /// This logs NULL but should not :(
    return Scaffold(
      body: SizedBox(
        width: double.maxFinite,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: [
            const Text('WELCOME'),
            (user == null) ? const Text('') : Text(user),
            const SizedBox(height: 50.0),
            ElevatedButton(
                onPressed: () async {
                  await ref.read(authenticationEndpoints).logout(context);
                },
                child: const Text('LOGOUT')),
          ],
        ),
      ),
    );
  }
}

class AuthenticationServices {
  static final _localAuth = LocalAuthentication();

  /// Login user
  ///
  static Future<Either<Failure, ParseUser>> login(String username, String password) async {
    try {
      // Cloud call - login
      final ParseResponse loginAttempt = await AuthenticationCloudCode.login(username, password);
      // Decrypt user object
      final dynamic decryptedUser = await CryptographicServices.fromServerDecryption(
        loginAttempt.result['data'],
        loginAttempt.result['keys'],
      );
      // Create user object from decrypted data
      final user = ParseUser(decryptedUser['username'], decryptedUser['password'], decryptedUser['email'])
        ..set('sessionToken', decryptedUser['sessionToken'])
        ..set('objectId', decryptedUser['objectId'])
        ..set('className', decryptedUser['className'])
        ..set('name', decryptedUser['name'])
        ..set('createdAt', decryptedUser['createdAt'])
        ..set('updatedAt', decryptedUser['updatedAt'])
        ..set('publicKey', decryptedUser['publicKey'])
        ..setACL(decryptedUser['ACL']);
      // Assign user session id
      ParseCoreData().setSessionId(user['sessionToken']!);
      return Right(user);
    } on SocketException {
      return Left(Failure('Internet connection issue'));
    } on ParseError catch (error) {
      return Left(Failure(error.message));
    } on TimeoutException {
      return Left(Failure('Request took too long'));
    }
  }

  /// Local authentication
  ///
  /// Biometric authentication attempt
  /// Failure => error.message
  /// bool => true (successfully authenticated)
  static Future<Either<Failure, bool>> biometricAuthentication() async {
    try {
      final bool biometricsAvailable = await _localAuth.canCheckBiometrics;
      if (biometricsAvailable) {
        List<BiometricType> availableBiometrics = await _localAuth.getAvailableBiometrics();
        if (availableBiometrics.contains(BiometricType.face)) {
          final localAuthResult = await _localAuth.authenticate(
            biometricOnly: true,
            iOSAuthStrings: const IOSAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FaceID',
              lockOut: 'Re-enable FaceID to use biometric authentication',
            ),
            androidAuthStrings: const AndroidAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FaceID',
              signInTitle: 'Face ID Required',
            ),
            localizedReason: 'Use face ID to login',
            useErrorDialogs: true,
            stickyAuth: true,
          );
          return Right(localAuthResult);
        } else if (availableBiometrics.contains(BiometricType.fingerprint)) {
          final localAuthResult = await _localAuth.authenticate(
            biometricOnly: true,
            iOSAuthStrings: const IOSAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FingerprintID',
              lockOut: 'Re-enable FingerprintID to use biometric authentication',
            ),
            androidAuthStrings: const AndroidAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FingerprintID',
              signInTitle: 'Use FingerprintID to sign in',
            ),
            localizedReason: 'Use biometric login',
            useErrorDialogs: true,
            stickyAuth: true,
          );
          return Right(localAuthResult);
        } else {
          return Left(Failure('Biometric authentication type not available'));
        }
      } else {
        return Left(Failure('Biometric authentication not available on your device'));
      }
    } on PlatformException catch (error) {
      return Left(Failure(error.message!));
    }
  }

...

}
</code>```

Logs

```<code>[log] {"className":"_User","objectId":"IfXR5pexoB","createdAt":"2022-02-12T06:25:58.633Z","updatedAt":"2022-02-12T06:25:58.633Z","username":"0010","email":"0010@0010.com","sessionToken":"r:edc1cb11618aa97a5c44b837a55d1a85","name":"0010","publicKey":"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl5yvZa3nhA9QCUey159hp92a9FFxf1sxap2tVxkikBATQDcXWKcJdkm+vUaVuLPvA6273XqWgV8AVlyIbf+KafWmr8kVXQ9HiJRVMUJb9dg+SKyUbZcoHs23RjUynSCoSKrbaLI1raaI5MorD/dxW2TkL/3UbnIr34rLywrs3Arbx8VD25yVbkA3qp+/N+6sQzK6eb9S8/FDWGn3GOYodMzbPVTDAX6AVwC8dONGrbBmZTm64ZIrLl69nMnRjoOy+MQWnT3dkniJSe5qe3tWXIxQu26lVPAubuY8T3a6KzqCvGa5MQtgA0dsfE6ud9LLtxXTWMVmSSg2yzf6AViZswIDAQAB","ACL":{"*":{"read":true},"IfXR5pexoB":{"read":true,"write":true}}}

[log] null
</code>```

答:
I just solved this. Pretty much a shot in the dark with one hand tied behind my back, I tried something out of randomness & desperation.

Solution:

I have set _authorizedUser to static

static ParseUser? _authorizedUser;

On deeper inspection I realize why static works is because somehow, somewhere along the line a second instance was made for _authorizedUser. I haven't a clue how and don't really care as having a static variable seems safer anyway. Hope this could help someone else.

Body:
No matter what I do, my variable _authorizedUser is coming back null.

I'm demoing biometric authentication for users, once user enters their username, if it matches one in the local database and biometric auth is a success, then user will automatically be logged in. This is currently hardcoded for username and password...

I can't get this to work in any configuration, there must be something wrong I haven't discovered. No matter what I do authorizedUser comes back null, even after confirming with log that it IS NOT NULL. Somehow it is bouncing back to null & I am getting null error. Previously I had _authorizedUser as a late variable but that was even worse. I think this may be an issue for Github but I wanted to make sure first.

Weirdly enough, if I login the old fashioned way entering username & password with button press, calling the same login method it works as intended. But as soon as I call login from inside my biometric authentication method, it's a no go. Am I using Either wrong or something? Any help greatly appreciated :)

enum NotifierState { initial, loading, loaded }

class AuthenticationEndpoints extends ChangeNotifier {
  // Authorized user
  ParseUser? _authorizedUser;
  ParseUser? get authorizedUser => _authorizedUser;
  Future<void> _setAuthorizedUser(ParseUser? user) async {
    _authorizedUser = user;
    log(_authorizedUser.toString());                      /// This logs proper object...
    notifyListeners();
  }

  /// Login user
  ///
  /// returns either Failure or Success
  /// Failure => [DialogError]
  /// Success => [_authorizedUser] = [user] & Navigate [HomeScreen]
  Future<void> login(BuildContext context, String username, String password) async {
    Either<Failure, ParseUser> user = await AuthenticationServices.login(username, password);
    user.fold(
      (failure) {
        showDialog(context: context, builder: (context) => DialogError(failure: Failure(failure.message)));
      },
      (user) {                        /// Correctly returns user object from server
        _setAuthorizedUser(user);
        Get.to(const HomeScreen());
      },
    );
  }

  /// Biometric authentication
  ///
  /// returns either Failure or true
  /// Failure => [DialogError]
  /// bool => [true] (authentication successful)
  Future<void> biometricAuthentication(BuildContext context) async {
    Either<Failure, bool> biometricAuthenticationAttempt =
        await AuthenticationServices.biometricAuthentication();
    biometricAuthenticationAttempt.fold(
      (failure) =>
          showDialog(context: context, builder: (context) => DialogError(failure: Failure(failure.message))),
      (authenticated) async {
        await login(context, '0010', '0010');
      },
    );
  }

...

}

Widget using variable

final authenticationEndpoints = ChangeNotifierProvider((ref) => AuthenticationEndpoints());

class Welcome extends ConsumerWidget {
  const Welcome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    String? user = ref.watch(authenticationEndpoints).authorizedUser?.username;
    log(user.toString());                     /// This logs NULL but should not :(
    return Scaffold(
      body: SizedBox(
        width: double.maxFinite,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: [
            const Text('WELCOME'),
            (user == null) ? const Text('') : Text(user),
            const SizedBox(height: 50.0),
            ElevatedButton(
                onPressed: () async {
                  await ref.read(authenticationEndpoints).logout(context);
                },
                child: const Text('LOGOUT')),
          ],
        ),
      ),
    );
  }
}

class AuthenticationServices {
  static final _localAuth = LocalAuthentication();

  /// Login user
  ///
  static Future<Either<Failure, ParseUser>> login(String username, String password) async {
    try {
      // Cloud call - login
      final ParseResponse loginAttempt = await AuthenticationCloudCode.login(username, password);
      // Decrypt user object
      final dynamic decryptedUser = await CryptographicServices.fromServerDecryption(
        loginAttempt.result['data'],
        loginAttempt.result['keys'],
      );
      // Create user object from decrypted data
      final user = ParseUser(decryptedUser['username'], decryptedUser['password'], decryptedUser['email'])
        ..set('sessionToken', decryptedUser['sessionToken'])
        ..set('objectId', decryptedUser['objectId'])
        ..set('className', decryptedUser['className'])
        ..set('name', decryptedUser['name'])
        ..set('createdAt', decryptedUser['createdAt'])
        ..set('updatedAt', decryptedUser['updatedAt'])
        ..set('publicKey', decryptedUser['publicKey'])
        ..setACL(decryptedUser['ACL']);
      // Assign user session id
      ParseCoreData().setSessionId(user['sessionToken']!);
      return Right(user);
    } on SocketException {
      return Left(Failure('Internet connection issue'));
    } on ParseError catch (error) {
      return Left(Failure(error.message));
    } on TimeoutException {
      return Left(Failure('Request took too long'));
    }
  }

  /// Local authentication
  ///
  /// Biometric authentication attempt
  /// Failure => error.message
  /// bool => true (successfully authenticated)
  static Future<Either<Failure, bool>> biometricAuthentication() async {
    try {
      final bool biometricsAvailable = await _localAuth.canCheckBiometrics;
      if (biometricsAvailable) {
        List<BiometricType> availableBiometrics = await _localAuth.getAvailableBiometrics();
        if (availableBiometrics.contains(BiometricType.face)) {
          final localAuthResult = await _localAuth.authenticate(
            biometricOnly: true,
            iOSAuthStrings: const IOSAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FaceID',
              lockOut: 'Re-enable FaceID to use biometric authentication',
            ),
            androidAuthStrings: const AndroidAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FaceID',
              signInTitle: 'Face ID Required',
            ),
            localizedReason: 'Use face ID to login',
            useErrorDialogs: true,
            stickyAuth: true,
          );
          return Right(localAuthResult);
        } else if (availableBiometrics.contains(BiometricType.fingerprint)) {
          final localAuthResult = await _localAuth.authenticate(
            biometricOnly: true,
            iOSAuthStrings: const IOSAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FingerprintID',
              lockOut: 'Re-enable FingerprintID to use biometric authentication',
            ),
            androidAuthStrings: const AndroidAuthMessages(
              cancelButton: 'CANCEL',
              goToSettingsButton: 'SETTINGS',
              goToSettingsDescription: 'You must setup FingerprintID',
              signInTitle: 'Use FingerprintID to sign in',
            ),
            localizedReason: 'Use biometric login',
            useErrorDialogs: true,
            stickyAuth: true,
          );
          return Right(localAuthResult);
        } else {
          return Left(Failure('Biometric authentication type not available'));
        }
      } else {
        return Left(Failure('Biometric authentication not available on your device'));
      }
    } on PlatformException catch (error) {
      return Left(Failure(error.message!));
    }
  }

...

}

Logs

[log] {"className":"_User","objectId":"IfXR5pexoB","createdAt":"2022-02-12T06:25:58.633Z","updatedAt":"2022-02-12T06:25:58.633Z","username":"0010","email":"0010@0010.com","sessionToken":"r:edc1cb11618aa97a5c44b837a55d1a85","name":"0010","publicKey":"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl5yvZa3nhA9QCUey159hp92a9FFxf1sxap2tVxkikBATQDcXWKcJdkm+vUaVuLPvA6273XqWgV8AVlyIbf+KafWmr8kVXQ9HiJRVMUJb9dg+SKyUbZcoHs23RjUynSCoSKrbaLI1raaI5MorD/dxW2TkL/3UbnIr34rLywrs3Arbx8VD25yVbkA3qp+/N+6sQzK6eb9S8/FDWGn3GOYodMzbPVTDAX6AVwC8dONGrbBmZTm64ZIrLl69nMnRjoOy+MQWnT3dkniJSe5qe3tWXIxQu26lVPAubuY8T3a6KzqCvGa5MQtgA0dsfE6ud9LLtxXTWMVmSSg2yzf6AViZswIDAQAB","ACL":{"*":{"read":true},"IfXR5pexoB":{"read":true,"write":true}}}

[log] null


问:
I am trying to create 4 buttons in HTML that calls the following functions such as Adding, Subtracting, Multiplying, dividing
I am new to JavaScript and I'm a bit confused about what I'm doing wrong. For this Assignment I need to create 4 buttons in HTML that calls the following functions such as adding, subtracting, multiplying and dividing. I am suppose to prompt the user to enter two numbers and then it will calculate it.

I figured out how to make one adding button but for some reason I am having trouble creating the other buttons for - * /. I am also not sure why it doesn't keep track of the calculations for the subtraction buttons and etc. I am kind of confused how to create multiple functions and buttons all in one program.

function add() {

  var num1, num2, num3;

  numAdd1 = parseInt(prompt("Enter First Number:"));
  numAdd2 = parseInt(prompt("Enter Second Number:"));
  numAdd3 = numAdd1 + numAdd2

  resultAdd = "Result is " + String(numAdd3)
  //document.write(numAdd3 + "
")

  document.getElementById("result").innerHTML = resultAdd;

}

function sub() {

  var sub1, sub2, sub3;

  sub1 = parseInt(prompt("Enter First Number:"));
  sub2 = parseInt(prompt("Enter Second Number:"));
  sub3 = sub1 - sub2

  result2 = "result is : " + String(numSub3)
  //document.write(Sub3 + "
")

  document.getElementById("result2").innerHTML = result2;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="add()">Press to Add</button>
<p id="result">Result:</p>

<button onclick="sub()">Press to Subtract</button>
<p id="result2">Result:</p>

<button onclick="Multiply()">Press to Multiply</button>
<p id="result">Result:</p>

<button onclick="Divide()">Press to Divide</button>
<p id="result2">Result:</p></code>```

答:
You kind of made a typo. At the end of the result2 variable "assignment"(which means to set the value of the variable), and you used the wrong name for the variable. numSub3 should be sub3.

```<code>result2 = "result is : " + String(sub3);
</code>```

Body:
I am new to JavaScript and I'm a bit confused about what I'm doing wrong. For this Assignment I need to create 4 buttons in HTML that calls the following functions such as adding, subtracting, multiplying and dividing. I am suppose to prompt the user to enter two numbers and then it will calculate it.

I figured out how to make one adding button but for some reason I am having trouble creating the other buttons for - * /. I am also not sure why it doesn't keep track of the calculations for the subtraction buttons and etc. I am kind of confused how to create multiple functions and buttons all in one program.

function add() {

  var num1, num2, num3;

  numAdd1 = parseInt(prompt("Enter First Number:"));
  numAdd2 = parseInt(prompt("Enter Second Number:"));
  numAdd3 = numAdd1 + numAdd2

  resultAdd = "Result is " + String(numAdd3)
  //document.write(numAdd3 + "
")

  document.getElementById("result").innerHTML = resultAdd;

}

function sub() {

  var sub1, sub2, sub3;

  sub1 = parseInt(prompt("Enter First Number:"));
  sub2 = parseInt(prompt("Enter Second Number:"));
  sub3 = sub1 - sub2

  result2 = "result is : " + String(numSub3)
  //document.write(Sub3 + "
")

  document.getElementById("result2").innerHTML = result2;

}

<button onclick="add()">Press to Add</button>

Result:

<button onclick="sub()">Press to Subtract</button>

Result:

<button onclick="Multiply()">Press to Multiply</button>

Result:

<button onclick="Divide()">Press to Divide</button>

Result:

Body:
You kind of made a typo. At the end of the result2 variable "assignment"(which means to set the value of the variable), and you used the wrong name for the variable. numSub3 should be sub3.

result2 = "result is : " + String(sub3);


问:
Remove leading zeros from string timestamp
Lua supports limited Expressions and Patterns

The time stamp is variable in the format DD:HH:MM:SS,FF (Days:Hours:Minutes:Seconds,Miliseconds)

The objective is to trim/truncate the timestamp by removing any leading zeros to represent as follow:

Example timestamps includes:

timestamp = 00:00:00:00,00 => 0

timestamp = 00:01:00:00,00 => 1:00:00,00

timestamp = 00:00:01:00,00 => 1:00,00

timestamp = 00:00:00:01,00 => 1,00

timestamp = 99:23:59:59,99 => 99:23:59:59,99

I am looking for a simple solution such as using gsub, TA

Body:
This regexp gets 5/5 but it is soo long

 local reg = '^[0]+[:]?[0]+[:]?[0]+[:]?[0]?'

    print('1 > ' .. '00:00:00:00,00 = ' .. ('00:00:00:00,00'):gsub(reg,''))
    print('2 > ' .. '00:01:00:00,00 = ' .. ('00:01:00:00,00'):gsub(reg,''))
    print('3 > ' .. '00:00:01:00,00 = ' .. ('00:00:01:00,00'):gsub(reg,''))
    print('4 > ' .. '00:00:00:01,00 = ' .. ('00:00:00:01,00'):gsub(reg,''))
    print('5 > ' .. '99:23:59:59,99 = ' .. ('99:23:59:59,99'):gsub(reg,''))


答:
try initializing the variable in the module.exports.initailize function</p>
```<code>module.exports.initialize = () => {
    let variable;
    variable = "123";
};

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

Title: nodejs variable undefined when exporting

Body:
try initializing the variable in the module.exports.initailize function

module.exports.initialize = () => {
    let variable;
    variable = "123";
};

module.exports.variable = variable;


问:
Segfault on accessing a C initialised ctypes structure element
I am trying to access elements of a structure from ctypes. The structure is created in an init function in the C code and pointer to it is returned to Python. The problem I am having is that I get a segfault when trying to access elements of the returned structure. Here is the code:

The C code (which I've called ctypes_struct_test.c):

```<code>#include <stdio.h>
#include <stdbool.h>

typedef struct {
    bool flag;
} simple_structure;

simple_structure * init()
{
    static simple_structure test_struct = {.flag = true};
    if (test_struct.flag) {
        printf("flag is set in C\n");
    }
    return &test_struct;
}
</code>```

The Python code (which I've called ctypes_struct_test.py):

```<code>#!/usr/bin/env python

import ctypes
import os

class SimpleStructure(ctypes.Structure):
    _fields_ = [('flag', ctypes.c_bool)]

class CtypesWrapperClass(object):

    def __init__(self):

        cwd = os.path.dirname(os.path.abspath(__file__))
        library_file = os.path.join(cwd,'libctypes_struct_test.so')

        self._c_ctypes_test = ctypes.CDLL(library_file)

        self._c_ctypes_test.init.restypes = ctypes.POINTER(SimpleStructure)
        self._c_ctypes_test.init.argtypes = []

        self.simple_structure = ctypes.cast(\
                self._c_ctypes_test.init(),\
                ctypes.POINTER(SimpleStructure))

a = CtypesWrapperClass()
print 'Python initialised fine'
print a.simple_structure.contents
print a.simple_structure.contents.flag
</code>```

The C is compiled under Linux as follows:

```<code>gcc -o ctypes_struct_test.os -c --std=c99 -fPIC ctypes_struct_test.c
gcc -o libctypes_struct_test.so -shared ctypes_struct_test.os
</code>```

On running python ctypes_struct_test.py, I get the following output:

```<code>flag is set in C
Python initialised fine
<__main__.SimpleStructure object at 0x166c680>
Segmentation fault
</code>```

Is there some problem with what I am trying to do, or the way I am trying to do it?

答:
You declare test_struct as a static local variable inside your init routine -- I'm suspicious of that at first blush. (Bear with me; my C is a bit rusty.)

Static local variables in C are supposed to persist across multiple calls to the same function, but their scope is the same as an automatic local variable -- and returning a pointer to an automatic local variable would certainly give you a segfault. Even if this would ordinarily work if you were calling that function from the same translation unit in C, the fact that you're calling it from Python (and that you're segfaulting as soon as you try to access the struct) is a red flag.

Instead of returning a pointer to a static variable, try using malloc() in your init routine and returning the pointer you get from that.

[[[ WARNING: this will result in a memory leak. ]]]

But that's OK; if the segfault goes away, you'll know that that was the problem. Then you can fix the memory leak by providing a second routine in your C code that calls free(), and making sure you invoke it from your python code when you're done with the struct.

Body:
I am trying to access elements of a structure from ctypes. The structure is created in an init function in the C code and pointer to it is returned to Python. The problem I am having is that I get a segfault when trying to access elements of the returned structure. Here is the code:

The C code (which I've called ctypes_struct_test.c):

#include <stdio.h>
#include <stdbool.h>

typedef struct {
    bool flag;
} simple_structure;

simple_structure * init()
{
    static simple_structure test_struct = {.flag = true};
    if (test_struct.flag) {
        printf("flag is set in C\n");
    }
    return &test_struct;
}

The Python code (which I've called ctypes_struct_test.py):

#!/usr/bin/env python

import ctypes
import os

class SimpleStructure(ctypes.Structure):
    _fields_ = [('flag', ctypes.c_bool)]

class CtypesWrapperClass(object):

    def __init__(self):

        cwd = os.path.dirname(os.path.abspath(__file__))
        library_file = os.path.join(cwd,'libctypes_struct_test.so')

        self._c_ctypes_test = ctypes.CDLL(library_file)

        self._c_ctypes_test.init.restypes = ctypes.POINTER(SimpleStructure)
        self._c_ctypes_test.init.argtypes = []

        self.simple_structure = ctypes.cast(\
                self._c_ctypes_test.init(),\
                ctypes.POINTER(SimpleStructure))

a = CtypesWrapperClass()
print 'Python initialised fine'
print a.simple_structure.contents
print a.simple_structure.contents.flag

The C is compiled under Linux as follows:

gcc -o ctypes_struct_test.os -c --std=c99 -fPIC ctypes_struct_test.c
gcc -o libctypes_struct_test.so -shared ctypes_struct_test.os

On running python ctypes_struct_test.py, I get the following output:

flag is set in C
Python initialised fine
<__main__.SimpleStructure object at 0x166c680>
Segmentation fault

Is there some problem with what I am trying to do, or the way I am trying to do it?


答:
If you want to customise how you display information in a class one option is to override ToString() for your Person class:

```<code>class Person
{
    ...
    // customize however you like
    public override string ToString() => $"{Name} {Surname}";
}
</code>```

Then to display in a single line, you could use string.Join():

```<code>Console.WriteLine(string.Join(", ", result));
</code>```

Or if you want each person on a new line:

```<code>result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);
</code>```

Title: Download values of list from json file

Body:
I have simple class

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public List<string> ParentsNames { get; set; }
}

And a json file

[
  {
    "Name": "Frank",
    "Surname": "Wilson",
    "Age": "52",
    "Login": "fwillock",
    "Password": "willock123",
    "ParentsNames": [
      "Charles",
      "Sarah"
    ]
  },
  {
    "Name": "Karen",
    "Surname": "Davies",
    "Age": "35",
    "Login": "kdavies",
    "Password": "davies123",
    "ParentsNames": [
      "Jason",
      "Angela"
    ]
  }
]

I need to get in console all names or surnames, existing in Person list. I tried to use something like this:

var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());

But i don't have any idea to use it in my code.
Thanks in advance.

Body:
If you want to customise how you display information in a class one option is to override ToString() for your Person class:

class Person
{
    ...
    // customize however you like
    public override string ToString() => $"{Name} {Surname}";
}

Then to display in a single line, you could use string.Join():

Console.WriteLine(string.Join(", ", result));

Or if you want each person on a new line:

result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);


问:
Flutter scrolling Row
i have a Row inside a listview that it does not scroll with the rest of listview content i wanted to be scrollable, by the wat the cards inside the listView scrolls fine but not the row, i tried to put it inside a Stack , but still same problem

here is my code

```<code>    return Scaffold(
  backgroundColor: Colors.white,
  appBar: AppBar()
  body: ListView(
    scrollDirection: Axis.vertical,
    shrinkWrap: true,
    children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.Prochaines_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xFFe0f2f1),
              ),
              child: Container(
                child: Text(
                  "Prochianes",
                  style: TextStyle(
                    color: Color(0xFF30a6ca),
                  ),
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.EnCours_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
              ),
              child: Text("En cours"),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.Termines_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
              ),
              child: Text("Terminés"),
            ),
          ),
        ],
      ),
      Container(width: 300, height: 200, color: Colors.black),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.red),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.yellow),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.green),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.brown),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.red),
    ],
  ),
);
</code>```

i have a Row inside a listview that it does not scroll with the rest of listview content i wanted to be scrollable, by the wat the cards inside the listView scrolls fine but not the row, i tried to put it inside a Stack , but still same problem

Thanks for your help.

答:
You can change the widget row to a ListView and do the following:</p>
```<code>Widget myWidget() {
  return SizedBox(
    height: 100, // Important to set a high
    child: ListView(
      scrollDirection: Axis.horizontal, // Set the scroll direction
      shrinkWrap: true, // Set the shrinkWrap to true
      children: <Widget>[
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        // You can add as many as you want ...
      ],
    ),
  );
}
</code>```

Title: Flutter scrolling Row

Body:
i have a Row inside a listview that it does not scroll with the rest of listview content i wanted to be scrollable, by the wat the cards inside the listView scrolls fine but not the row, i tried to put it inside a Stack , but still same problem

here is my code

    return Scaffold(
  backgroundColor: Colors.white,
  appBar: AppBar()
  body: ListView(
    scrollDirection: Axis.vertical,
    shrinkWrap: true,
    children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.Prochaines_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xFFe0f2f1),
              ),
              child: Container(
                child: Text(
                  "Prochianes",
                  style: TextStyle(
                    color: Color(0xFF30a6ca),
                  ),
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.EnCours_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
              ),
              child: Text("En cours"),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, route.Termines_route);
            },
            child: Container(
              padding: EdgeInsets.all(17.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
              ),
              child: Text("Terminés"),
            ),
          ),
        ],
      ),
      Container(width: 300, height: 200, color: Colors.black),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.red),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.yellow),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.green),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.brown),
      SizedBox(
        height: 30,
      ),
      Container(width: 300, height: 200, color: Colors.red),
    ],
  ),
);

i have a Row inside a listview that it does not scroll with the rest of listview content i wanted to be scrollable, by the wat the cards inside the listView scrolls fine but not the row, i tried to put it inside a Stack , but still same problem

Thanks for your help.

Body:
You can change the widget row to a ListView and do the following:

Widget myWidget() {
  return SizedBox(
    height: 100, // Important to set a high
    child: ListView(
      scrollDirection: Axis.horizontal, // Set the scroll direction
      shrinkWrap: true, // Set the shrinkWrap to true
      children: <Widget>[
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        Container(width: 100, height: 100, color: Colors.red),
        // You can add as many as you want ...
      ],
    ),
  );
}