问:
Iterate over two strings checking to see if it matches with its pair
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

```<code>    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }
</code>```

'''

答:
The numerical sum of chars T & A and G & C is fixed and unique for legal nucleobase pairs.  So you just need to ensure that the corresponding bases have one of those sums.

```<code>String seq1 = "TTCGATGGAGCTGTA";
String seq2 = "TAGCTAGCTCGGCATGA";
System.out.println(count_mismatches(seq1, seq2));
</code>```

prints

```<code>5
</code>```

find max length to iterate

establish fixed sums for comparison

iterate and compare to expected pairing and update count appropriately

```<code>public static int count_mismatches(String seq1, String seq2) {
    int len1 = seq1.length();
    int len2 = seq2.length();
    int len = len1;
    if (len1 > len2) {
        len = len2;
    }

    int sumTA = 'T'+'A';
    int sumGC = 'G'+'C';

    int misMatchCount = Math.abs(len1-len2);
    for (int i = 0; i < len; i++) {
        int pair = seq1.charAt(i) + seq2.charAt(i);
        if (pair != sumTA && pair != sumGC) {
            misMatchCount++;
        }
    }
    return misMatchCount;
}
</code>```

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
The numerical sum of chars T & A and G & C is fixed and unique for legal nucleobase pairs.  So you just need to ensure that the corresponding bases have one of those sums.

String seq1 = "TTCGATGGAGCTGTA";
String seq2 = "TAGCTAGCTCGGCATGA";
System.out.println(count_mismatches(seq1, seq2));

prints

5

find max length to iterate

establish fixed sums for comparison

iterate and compare to expected pairing and update count appropriately

public static int count_mismatches(String seq1, String seq2) {
    int len1 = seq1.length();
    int len2 = seq2.length();
    int len = len1;
    if (len1 > len2) {
        len = len2;
    }

    int sumTA = 'T'+'A';
    int sumGC = 'G'+'C';

    int misMatchCount = Math.abs(len1-len2);
    for (int i = 0; i < len; i++) {
        int pair = seq1.charAt(i) + seq2.charAt(i);
        if (pair != sumTA && pair != sumGC) {
            misMatchCount++;
        }
    }
    return misMatchCount;
}


来源: stackexchange

问:
How to create a new character column removing text from another column in dataframe in r
I have the following data frame in R

```<code>East    24  Consumer    7/18/2018 0:00  Second Class    Pennsylvania    Chairs  USD71.37
East    29  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD9.61
East    33  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD6.85
East    199 Corporate   7/13/2018 0:00  Standard Class  Pennsylvania    Binders USD2.94
East    216 Corporate   1/9/2016 0:00   Standard Class  Ohio    Machines    USD1188
East    222 Consumer    12/27/2016 0:00 First Class Ohio    Binders USD24
East    224 Consumer    12/27/2016 0:00 First Class Ohio    Machines    USD252
East    331 Consumer    9/1/2017 0:00   First Class Pennsylvania    Binders USD28
East    333 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD40
East    334 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD8
</code>```

The last column is sales which is a character - my problem is I want to create a new column with sales numbers that has just the numbers  - please help if able!!!!!

答:
If the column is called "a", you can sub set the string and then convert to numeric like this:</p>
```<code>> a <- c("USD71.37","USD9.61")
>
> as.numeric(str_sub(a,4,-1))
[1] 71.37  9.61
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following data frame in R

East    24  Consumer    7/18/2018 0:00  Second Class    Pennsylvania    Chairs  USD71.37
East    29  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD9.61
East    33  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD6.85
East    199 Corporate   7/13/2018 0:00  Standard Class  Pennsylvania    Binders USD2.94
East    216 Corporate   1/9/2016 0:00   Standard Class  Ohio    Machines    USD1188
East    222 Consumer    12/27/2016 0:00 First Class Ohio    Binders USD24
East    224 Consumer    12/27/2016 0:00 First Class Ohio    Machines    USD252
East    331 Consumer    9/1/2017 0:00   First Class Pennsylvania    Binders USD28
East    333 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD40
East    334 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD8

The last column is sales which is a character - my problem is I want to create a new column with sales numbers that has just the numbers  - please help if able!!!!!

Body:
If the column is called "a", you can sub set the string and then convert to numeric like this:

> a <- c("USD71.37","USD9.61")
>
> as.numeric(str_sub(a,4,-1))
[1] 71.37  9.61


问:
How to call a superclass method using Java reflection
I have two classes:

```<code>public class A {
    public Object method() {...}
}

public class B extends A {
    @Override
    public Object method() {...}
}
</code>```

I have an instance of B.  How do I call A.method() from b?  Basically, the same effect as calling super.method() from B.

```<code>B b = new B();
Class<?> superclass = b.getClass().getSuperclass();
Method method = superclass.getMethod("method", ArrayUtils.EMPTY_CLASS_ARRAY);
Object value = method.invoke(obj, ArrayUtils.EMPTY_OBJECT_ARRAY);
</code>```

But the above code will still invoke B.method().

答:
I don't know how to do it in the case when You want to do the trick for included libraries, because the reflection doesn't work, but for my own code I would do this simple workaround:

```<code>public class A {
    public Object method() {...}
}

public class B extends A {
    @Override
    public Object method() {...}

    public Object methodSuper() {
        return super.method();
    }
}
</code>```

For simple cases this is OK, for some automatic invocation not so much. For instance, when You have a chain

```<code>A1 super A2 super A3 ... super An
</code>```

of inheriting classes, all overriding a method m. Then invoking m from A1 on an instance of An would require too much bad coding :-)

Body:
I have two classes:

public class A {
    public Object method() {...}
}

public class B extends A {
    @Override
    public Object method() {...}
}

I have an instance of B.  How do I call A.method() from b?  Basically, the same effect as calling super.method() from B.

B b = new B();
Class<?> superclass = b.getClass().getSuperclass();
Method method = superclass.getMethod("method", ArrayUtils.EMPTY_CLASS_ARRAY);
Object value = method.invoke(obj, ArrayUtils.EMPTY_OBJECT_ARRAY);

But the above code will still invoke B.method().

Body:
I don't know how to do it in the case when You want to do the trick for included libraries, because the reflection doesn't work, but for my own code I would do this simple workaround:

public class A {
    public Object method() {...}
}

public class B extends A {
    @Override
    public Object method() {...}

    public Object methodSuper() {
        return super.method();
    }
}

For simple cases this is OK, for some automatic invocation not so much. For instance, when You have a chain

A1 super A2 super A3 ... super An

of inheriting classes, all overriding a method m. Then invoking m from A1 on an instance of An would require too much bad coding :-)

ContentLicense: CC BY-SA 3.0


问:
How to make an app.route() in Flask only functional if you are coming from a specific URL?
I'm creating a project to learn how to use Stripe and work together with a registration template. My integration with Stripe is working, I can successfully make a payment and after the payment is done, I'm redirected to my registration template.

The problem is, you should only get access to the registration template after going through the Stripe integration, but what is happening is anyone who access the '/register' URL manually can by pass the payment stage and register himself in the registration template.

The route I'm using in the process is:

```<code>@app.route('/stripe_pay')
def stripe_pay():
    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price': '{{ PRICE ID }}',
            'quantity': 1,
        }],
        mode='subscription',
        success_url=url_for('register', _external=True),
        cancel_url=url_for('signup', _external=True),
    )
    return {
        'checkout_session_id': session['id'],
        'checkout_public_key': app.config['STRIPE_PUBLIC_KEY'],
    }
</code>```

The '/register' route performs user data collection and then writes down all the information in a database. All is working fine with the process.

```<code>@app.route('/register')
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        todb = c_personal_info( first_name = form.first_name.data,
                            last_name = form.last_name.data,
                            email = form.email.data,
                            password = form.password.data,
                            subscription='M')
        with db.session.begin():
            db.session.add(todb)
        flash('Thanks for registering! You can now login!', category="success")
        return redirect(url_for('login'))
    return render_template('register.html', form = form)
</code>```

The session is not authenticated, as the '/register' template is actually where you would create your credentials to log in.

My question is how do I make the '/register' end point only accessible when you are coming from the '/stripe_pay' end point? I also would love to hear your ideas and different aproaches to this.

答:
Study using a decorator to handle your problem. See https://flask.palletsprojects.com/en/2.0.x/tutorial/views/ for example.

```<code>def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view
</code>```

This piece of code will require users to login first before able to access any page having the @login_required decorator.

Body:
I'm creating a project to learn how to use Stripe and work together with a registration template. My integration with Stripe is working, I can successfully make a payment and after the payment is done, I'm redirected to my registration template.

The problem is, you should only get access to the registration template after going through the Stripe integration, but what is happening is anyone who access the '/register' URL manually can by pass the payment stage and register himself in the registration template.

The route I'm using in the process is:

@app.route('/stripe_pay')
def stripe_pay():
    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price': '{{ PRICE ID }}',
            'quantity': 1,
        }],
        mode='subscription',
        success_url=url_for('register', _external=True),
        cancel_url=url_for('signup', _external=True),
    )
    return {
        'checkout_session_id': session['id'],
        'checkout_public_key': app.config['STRIPE_PUBLIC_KEY'],
    }

The '/register' route performs user data collection and then writes down all the information in a database. All is working fine with the process.

@app.route('/register')
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        todb = c_personal_info( first_name = form.first_name.data,
                            last_name = form.last_name.data,
                            email = form.email.data,
                            password = form.password.data,
                            subscription='M')
        with db.session.begin():
            db.session.add(todb)
        flash('Thanks for registering! You can now login!', category="success")
        return redirect(url_for('login'))
    return render_template('register.html', form = form)

The session is not authenticated, as the '/register' template is actually where you would create your credentials to log in.

My question is how do I make the '/register' end point only accessible when you are coming from the '/stripe_pay' end point? I also would love to hear your ideas and different aproaches to this.

Body:
Study using a decorator to handle your problem. See https://flask.palletsprojects.com/en/2.0.x/tutorial/views/ for example.

def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view

This piece of code will require users to login first before able to access any page having the @login_required decorator.


问:
How can I read the pdf names in the file in the ftp folder in C#?
I want to connect to the folder via ftp and get the file names in the folder as a list. I want to compare the names in this list with the names in my own database and see if there are different names. How can I get the file names in that folder as a list with my ftp connection and the folder information I want to connect.

How can I read and extract the names 1.pdf,A.pdf,c4.pdf ... etc in the Document folder in the ftp folder as a list.

For example:   Document folder include :  1.pdf,A.pdf,c4.pdf

I want to :   List ftpdocumentincludesname= List();

答:
FTP is relatively old and few sites actually still really offer FTP listings most are switching to FTPoverHTTPS:// one example site which is still showing both is

FTP://ftp.gnu.org and it depends how long they may allow simple views such as Windows Explorer, many may only offer an HTML style interface.

The better ones will include a readme file listing, thus no need to make your own. but if you must you can copy&paste or "save as" site_blahblah.htm

If you need better there are dedicated FTP site browsers, that allow for easy access and listings.

you can for simple sites like above  simply write a response file say pdf.txt

```<code>user Anonymous
literal pasv
ls *.pdf
bye
</code>```

and run it via commandline ftp -i -s:pdf.txt -n ftp.gnu.org
the response will be something like

```<code>Connected to ftp.gnu.org.
220 GNU FTP server ready.
ftp> user Anonymous
230 Login successful.
ftp> literal pasv
227 Entering Passive Mode (209,51,188,20,108,5).
ftp> ls *.pdf
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.

blahblah.pdf
blah.pdf
blahblahblah.pdf

226 Directory send OK.
ftp> bye
221 Goodbye.
</code>```

If you want more details, so for example in place of ls *.pdf lets use real world dir *.gz and we get:-

```<code>ftp> dir *.gz
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-rw-r--    1 0        3003       240409 Feb 06 21:01 find.txt.gz
-rw-rw-r--    1 0        3003       462613 Feb 06 21:01 ls-lrRt.txt.gz
-rw-rw-r--    1 0        3003       543098 Feb 06 21:01 tree.json.gz
226 Directory send OK.
</code>```

For ad hoc listings its quicker to cut and paste the folder as above. However as pointed out you want to use C# so use the stock listing and work iteratively around that.

```<code>using System;
using System.IO;
using System.Net;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            Console.WriteLine(reader.ReadToEnd());

            Console.WriteLine($"Directory List Complete, status {response.StatusDescription}");

            reader.Close();
            response.Close();
        }
    }
}
</code>```

Body:
FTP is relatively old and few sites actually still really offer FTP listings most are switching to FTPoverHTTPS:// one example site which is still showing both is

FTP://ftp.gnu.org and it depends how long they may allow simple views such as Windows Explorer, many may only offer an HTML style interface.

The better ones will include a readme file listing, thus no need to make your own. but if you must you can copy&paste or "save as" site_blahblah.htm

If you need better there are dedicated FTP site browsers, that allow for easy access and listings.

you can for simple sites like above  simply write a response file say pdf.txt

user Anonymous
literal pasv
ls *.pdf
bye

and run it via commandline ftp -i -s:pdf.txt -n ftp.gnu.org
the response will be something like

Connected to ftp.gnu.org.
220 GNU FTP server ready.
ftp> user Anonymous
230 Login successful.
ftp> literal pasv
227 Entering Passive Mode (209,51,188,20,108,5).
ftp> ls *.pdf
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.

blahblah.pdf
blah.pdf
blahblahblah.pdf

226 Directory send OK.
ftp> bye
221 Goodbye.

If you want more details, so for example in place of ls *.pdf lets use real world dir *.gz and we get:-

ftp> dir *.gz
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-rw-r--    1 0        3003       240409 Feb 06 21:01 find.txt.gz
-rw-rw-r--    1 0        3003       462613 Feb 06 21:01 ls-lrRt.txt.gz
-rw-rw-r--    1 0        3003       543098 Feb 06 21:01 tree.json.gz
226 Directory send OK.

For ad hoc listings its quicker to cut and paste the folder as above. However as pointed out you want to use C# so use the stock listing and work iteratively around that.

using System;
using System.IO;
using System.Net;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            Console.WriteLine(reader.ReadToEnd());

            Console.WriteLine($"Directory List Complete, status {response.StatusDescription}");

            reader.Close();
            response.Close();
        }
    }
}


问:
How do I build a parameterized third-party library in cmake?
I have a project in which I have a third party library checked out as a git submodule. The third party library is just source code with no build system. In addition, The third party library must configured on a per-executable basis by way of compiler definitions and selectively compiling only the parts of the library that I need. I use this library in a lot of different repositories, so I want to make a reusable component to generate an instantiation of the library for any particular executable.

The way I've currently attempted this is by creating a generate_thirdparty.cmake. This file looks something like this:

```<code>function(generate_thirdparty parameters)
    # several calls to add_library for the different components of this third party library
    # the generated libraries depend on the parameters argument
    # the parameters configure compile definitions and which source files are compiled
endfunction()
</code>```

Then in my project CMakeLists.txt I have something like:

```<code>cmake_minimum_required(VERSION 3.8)
project(test C)

include(generate_thirdparty.cmake)
set(parameters <some parameters here>)
generate_thirdparty(${parameters})

add_executable(my_exe main.c)
target_link_libraries(my_exe <library names from generate_thirdparty>)
</code>```

It seems like what I have works, but I'm confused on how you're supposed to do this. I've read through other posts and seen people suggest using find_package or ExternalProject_add. Given a third party repository that contains source code and no build system, which you have no control over, how do you create a reusable way to build that library, especially in the case that the library must be parameterized any given executable?

EDIT: I would like to have the flexibility to have multiple instantiations of the library in the same project.

答:
Let's sum up:

The third-party library does not provide its own build.

You need many instantiations of the library within a single build.

You use these instantiations across multiple different repositories.

I think you're pretty much taking the right approach. Let's call the third-party library libFoo for brevity. Here's what I think you should do...

Create a wrapper repository for libFoo that contains a FindFoo.cmake file and the actual foo repository submodule next to it. This is to avoid the contents of FindFoo.cmake from being independently versioned across your various projects.

Include the wrapper as your submodule in dependent projects, say in the directory third_party/foo_wrapper

In those dependent projects, write:

```<code>list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/third_party/foo_wrapper")
find_package(Foo REQUIRED)

generate_foo(config1 ...)
generate_foo(config2 ...)

add_executable(app1 src/app1/main.cpp)
target_link_libraries(app1 PRIVATE foo::config1)

add_executable(app2 src/app2/main.cpp)
target_link_libraries(app2 PRIVATE foo::config2)
</code>```

The contents of FindFoo.cmake will simply be:

```<code>cmake_minimum_required(VERSION 3.18)

function(generate_foo target)
   # Use CMAKE_CURRENT_FUNCTION_LIST_DIR to reference foo's source files
   # for example:

   set(sources "src/src1.cpp" "src/src2.cpp" ...)
   list(TRANSFORM sources PREPEND "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/foo/")

   add_library(${target} ${sources})
   add_library(foo::${target} ALIAS ${target})

   # Do other things with ARGN
endfunction()

# Define a version for this dependency + script combo.
set(Foo_VERSION 0.1.0)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo VERSION_VAR Foo_VERSION
                                  HANDLE_COMPONENTS)
</code>```

The CMAKE_CURRENT_FUNCTION_LIST_DIR is the absolute path to the file containing the function being called. Remember that this is the root of your wrapper repository, so the actual sources for libFoo will be in the adjacent foo directory. list(TRANSFORM) lets us write relative paths in the sources list that get converted to absolute paths for the sake of add_library (passing a relative path to add_library would be relative to the caller's source directory).

I also create an ALIAS target so that callers of generate_foo can link to the alias. This is important because CMake considers names that contain :: to be targets when a library is expected. This very helpfully turns typos from unintended linker flags into configure-time "target not found" errors.

Then we define the function like normal and call the find_package_handle_standard_args to handle find_package arguments like REQUIRED, COMPONENTS (even just to check that none were incorrectly specified), and VERSION. See the docs for it, here: https://cmake.org/cmake/help/latest/module/FindPackageHandleStandardArgs.html

Body:
I have a project in which I have a third party library checked out as a git submodule. The third party library is just source code with no build system. In addition, The third party library must configured on a per-executable basis by way of compiler definitions and selectively compiling only the parts of the library that I need. I use this library in a lot of different repositories, so I want to make a reusable component to generate an instantiation of the library for any particular executable.

The way I've currently attempted this is by creating a generate_thirdparty.cmake. This file looks something like this:

function(generate_thirdparty parameters)
    # several calls to add_library for the different components of this third party library
    # the generated libraries depend on the parameters argument
    # the parameters configure compile definitions and which source files are compiled
endfunction()

Then in my project CMakeLists.txt I have something like:

cmake_minimum_required(VERSION 3.8)
project(test C)

include(generate_thirdparty.cmake)
set(parameters <some parameters here>)
generate_thirdparty(${parameters})

add_executable(my_exe main.c)
target_link_libraries(my_exe <library names from generate_thirdparty>)

It seems like what I have works, but I'm confused on how you're supposed to do this. I've read through other posts and seen people suggest using find_package or ExternalProject_add. Given a third party repository that contains source code and no build system, which you have no control over, how do you create a reusable way to build that library, especially in the case that the library must be parameterized any given executable?

EDIT: I would like to have the flexibility to have multiple instantiations of the library in the same project.

Body:
Let's sum up:

The third-party library does not provide its own build.

You need many instantiations of the library within a single build.

You use these instantiations across multiple different repositories.

I think you're pretty much taking the right approach. Let's call the third-party library libFoo for brevity. Here's what I think you should do...

Create a wrapper repository for libFoo that contains a FindFoo.cmake file and the actual foo repository submodule next to it. This is to avoid the contents of FindFoo.cmake from being independently versioned across your various projects.

Include the wrapper as your submodule in dependent projects, say in the directory third_party/foo_wrapper

In those dependent projects, write:

list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/third_party/foo_wrapper")
find_package(Foo REQUIRED)

generate_foo(config1 ...)
generate_foo(config2 ...)

add_executable(app1 src/app1/main.cpp)
target_link_libraries(app1 PRIVATE foo::config1)

add_executable(app2 src/app2/main.cpp)
target_link_libraries(app2 PRIVATE foo::config2)

The contents of FindFoo.cmake will simply be:

cmake_minimum_required(VERSION 3.18)

function(generate_foo target)
   # Use CMAKE_CURRENT_FUNCTION_LIST_DIR to reference foo's source files
   # for example:

   set(sources "src/src1.cpp" "src/src2.cpp" ...)
   list(TRANSFORM sources PREPEND "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/foo/")

   add_library(${target} ${sources})
   add_library(foo::${target} ALIAS ${target})

   # Do other things with ARGN
endfunction()

# Define a version for this dependency + script combo.
set(Foo_VERSION 0.1.0)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo VERSION_VAR Foo_VERSION
                                  HANDLE_COMPONENTS)

The CMAKE_CURRENT_FUNCTION_LIST_DIR is the absolute path to the file containing the function being called. Remember that this is the root of your wrapper repository, so the actual sources for libFoo will be in the adjacent foo directory. list(TRANSFORM) lets us write relative paths in the sources list that get converted to absolute paths for the sake of add_library (passing a relative path to add_library would be relative to the caller's source directory).

I also create an ALIAS target so that callers of generate_foo can link to the alias. This is important because CMake considers names that contain :: to be targets when a library is expected. This very helpfully turns typos from unintended linker flags into configure-time "target not found" errors.

Then we define the function like normal and call the find_package_handle_standard_args to handle find_package arguments like REQUIRED, COMPONENTS (even just to check that none were incorrectly specified), and VERSION. See the docs for it, here: https://cmake.org/cmake/help/latest/module/FindPackageHandleStandardArgs.html


问:
Problem with code compatibility with Python 3.9 - "TypeError: a bytes-like object is required, not 'str'"
While trying to run a telemetry python application on Python 3.9, it fails with the error "TypeError: a bytes-like object is required, not 'str'"

Attempting to fix the code by changing 'r' to 'rb' (and 'w' to 'wb') as suggested elsewhere results in a different error.

Unfortunately, I can't figure this one out.  Can anyone help me identify the problem here?  I'm very new to this.  Thanks in advance.

```<code>  def __init__(self):
    try:
      with open(STATUS_FILE, 'r') as sfd:
        self.st_data = pickle.loads(sfd.read())
    except IOError:
      self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

    self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

  def __repr__(self):
    return "%s %s" % (self.__class__, self.st_data)

  def save(self):
    self.st_data['timestamp'] = int(time.time())
    try:
      with open(STATUS_FILE, 'w') as sfd:
        sfd.write(pickle.dumps(self.st_data))
    except IOError as err:
      print(err)
</code>```

答:
pickle.loads() takes a bytes-like object as the first argument. You're sending a string. See: https://docs.python.org/3/library/pickle.html#pickle.loads

Converting a string to bytes is covered in more depth here: Best way to convert string to bytes in Python 3?

The easiest way for you is probably:

```<code>my_data = bytes(sfd.read(), 'utf-8')
</code>```

Body:
While trying to run a telemetry python application on Python 3.9, it fails with the error "TypeError: a bytes-like object is required, not 'str'"

Attempting to fix the code by changing 'r' to 'rb' (and 'w' to 'wb') as suggested elsewhere results in a different error.

Unfortunately, I can't figure this one out.  Can anyone help me identify the problem here?  I'm very new to this.  Thanks in advance.

  def __init__(self):
    try:
      with open(STATUS_FILE, 'r') as sfd:
        self.st_data = pickle.loads(sfd.read())
    except IOError:
      self.st_data = dict(seq=0, timestamp=int(time.time()), rx_packets=0, tx_packets=0)

    self.st_data['seq'] = (self.st_data['seq'] % 999) + 1

  def __repr__(self):
    return "%s %s" % (self.__class__, self.st_data)

  def save(self):
    self.st_data['timestamp'] = int(time.time())
    try:
      with open(STATUS_FILE, 'w') as sfd:
        sfd.write(pickle.dumps(self.st_data))
    except IOError as err:
      print(err)

Body:
pickle.loads() takes a bytes-like object as the first argument. You're sending a string. See: https://docs.python.org/3/library/pickle.html#pickle.loads

Converting a string to bytes is covered in more depth here: Best way to convert string to bytes in Python 3?

The easiest way for you is probably:

my_data = bytes(sfd.read(), 'utf-8')


问:
how to count observations used and deleted when using a regression in r
I have a dataset I am working with that has multiple variables. Some of these variables have observations that are NA. After running the regression there are some observations deleted because of the NA. I subset my data with the following code:

```<code>jsubset= jtrain %>% select(2,11,23,24,28)
</code>```

Which returned the following output:
jsubset

```<code>A tibble: 471 x 5
    fcode   d89 cgrant clemploy cgrant_1
    <dbl> <dbl>  <dbl>    <dbl>    <dbl>
 1 410032     0      0  NA            NA
 2 410032     0      0   0.270         0
 3 410032     1      0  -0.0630        0
 4 410440     0      0  NA            NA
 5 410440     0      0   0.0800        0
 6 410440     1      0   0.0741        0
 7 410495     0      0  NA            NA
 8 410495     0      0   0.223         0
 9 410495     1      0  -0.0408        0
10 410500     0      0  NA            NA
 ... with 461 more rows
</code>```

How would I separate FCODES that have values for the remaining columns and FCODES that while they have values for some columns there are NA? Or is it easier to count observations used and deleted from the regression? I know the command in STATA is e(sample) that does this easier but trying to replicate in R.

答:
Arranging by NA values

Should be straight forward if you have a proper data frame. First, I just copied your data into a text file, named it, then turned it into a data frame:

```<code>slack <- read.table("slack.txt")
colnames(slack) <- c("fcode",
                     "d89",
                     "cgrant",
                     "clemploy",
                     "cgrant_1")
slack <- data.frame(slack)
</code>```

Then just arrange the values, which will naturally reorder the NA values you mentioned:

```<code>slack %>%
  arrange(cgrant_1)
</code>```

Giving you this:

```<code>   fcode    d89 cgrant clemploy cgrant_1
1      3 410032      1       0  -0.0630
2      9 410495      1       0  -0.0408
3      6 410440      1       0   0.0741
4      5 410440      0       0   0.0800
5      8 410495      0       0   0.2230
6      2 410032      0       0   0.2700
7      1 410032      0       0       NA
8      4 410440      0       0       NA
9      7 410495      0       0       NA
10    10 410500      0       0       NA
</code>```

Removing NA values

If you just want to get rid of the NA values:

```<code>slack %>%
  na.omit()
</code>```

Which gives you:

```<code>  fcode    d89 cgrant cemploy cgrant_1
2     2 410032      0       0   0.2700
3     3 410032      1       0  -0.0630
5     5 410440      0       0   0.0800
6     6 410440      1       0   0.0741
8     8 410495      0       0   0.2230
9     9 410495      1       0  -0.0408
</code>```

Subset data with NA values removed

You can also subset that data into a new dataframe with the following code:

```<code># NA Removed Dataframe:
no_na_slack <- slack %>%
      na.omit()

# Is NA Dataframe:
is_na_slack <- slack %>%
      filter_all(any_vars(is.na(.)))
</code>```

Body:
I have a dataset I am working with that has multiple variables. Some of these variables have observations that are NA. After running the regression there are some observations deleted because of the NA. I subset my data with the following code:

jsubset= jtrain %>% select(2,11,23,24,28)

Which returned the following output:
jsubset

A tibble: 471 x 5
    fcode   d89 cgrant clemploy cgrant_1
    <dbl> <dbl>  <dbl>    <dbl>    <dbl>
 1 410032     0      0  NA            NA
 2 410032     0      0   0.270         0
 3 410032     1      0  -0.0630        0
 4 410440     0      0  NA            NA
 5 410440     0      0   0.0800        0
 6 410440     1      0   0.0741        0
 7 410495     0      0  NA            NA
 8 410495     0      0   0.223         0
 9 410495     1      0  -0.0408        0
10 410500     0      0  NA            NA
 ... with 461 more rows

How would I separate FCODES that have values for the remaining columns and FCODES that while they have values for some columns there are NA? Or is it easier to count observations used and deleted from the regression? I know the command in STATA is e(sample) that does this easier but trying to replicate in R.

Body:
Arranging by NA values

Should be straight forward if you have a proper data frame. First, I just copied your data into a text file, named it, then turned it into a data frame:

slack <- read.table("slack.txt")
colnames(slack) <- c("fcode",
                     "d89",
                     "cgrant",
                     "clemploy",
                     "cgrant_1")
slack <- data.frame(slack)

Then just arrange the values, which will naturally reorder the NA values you mentioned:

slack %>%
  arrange(cgrant_1)

Giving you this:

   fcode    d89 cgrant clemploy cgrant_1
1      3 410032      1       0  -0.0630
2      9 410495      1       0  -0.0408
3      6 410440      1       0   0.0741
4      5 410440      0       0   0.0800
5      8 410495      0       0   0.2230
6      2 410032      0       0   0.2700
7      1 410032      0       0       NA
8      4 410440      0       0       NA
9      7 410495      0       0       NA
10    10 410500      0       0       NA

Removing NA values

If you just want to get rid of the NA values:

slack %>%
  na.omit()

Which gives you:

  fcode    d89 cgrant cemploy cgrant_1
2     2 410032      0       0   0.2700
3     3 410032      1       0  -0.0630
5     5 410440      0       0   0.0800
6     6 410440      1       0   0.0741
8     8 410495      0       0   0.2230
9     9 410495      1       0  -0.0408

Subset data with NA values removed

You can also subset that data into a new dataframe with the following code:

# NA Removed Dataframe:
no_na_slack <- slack %>%
      na.omit()

# Is NA Dataframe:
is_na_slack <- slack %>%
      filter_all(any_vars(is.na(.)))


问:
How to plot a pre-build map from google maps on a MapView
I'm trying to read a map from a link (http://maps.google.com/maps/ms?msid=216892338463540803496.000494dd57eb5ebce6db2&msa=0) and plot it on a MapView, is it possible?</p>

答:
Look at this tutorial: http://codemagician.wordpress.com/2010/05/06/android-google-mapview-tutorial-done-right/</p>

```<code>@Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 MapView mapView = (MapView) findViewById(R.id.mapview);
 mapView.setBuiltInZoomControls(true);

 List<Overlay> mapOverlays = mapView.getOverlays();
 Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
 HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,this);
 GeoPoint point = new GeoPoint(30443769,-91158458);
 OverlayItem overlayitem = new OverlayItem(point, "Laissez les bon temps rouler!", "I'm in Louisiana!");

 GeoPoint point2 = new GeoPoint(17385812,78480667);
 OverlayItem overlayitem2 = new OverlayItem(point2, "Namashkaar!", "I'm in Hyderabad, India!");

 itemizedoverlay.addOverlay(overlayitem);
 itemizedoverlay.addOverlay(overlayitem2);

 mapOverlays.add(itemizedoverlay);
 }
 @Override
 protected boolean isRouteDisplayed()
 {
 return false;
 }
}
</code>```

Body:
Look at this tutorial: http://codemagician.wordpress.com/2010/05/06/android-google-mapview-tutorial-done-right/

@Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 MapView mapView = (MapView) findViewById(R.id.mapview);
 mapView.setBuiltInZoomControls(true);

 List<Overlay> mapOverlays = mapView.getOverlays();
 Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
 HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,this);
 GeoPoint point = new GeoPoint(30443769,-91158458);
 OverlayItem overlayitem = new OverlayItem(point, "Laissez les bon temps rouler!", "I'm in Louisiana!");

 GeoPoint point2 = new GeoPoint(17385812,78480667);
 OverlayItem overlayitem2 = new OverlayItem(point2, "Namashkaar!", "I'm in Hyderabad, India!");

 itemizedoverlay.addOverlay(overlayitem);
 itemizedoverlay.addOverlay(overlayitem2);

 mapOverlays.add(itemizedoverlay);
 }
 @Override
 protected boolean isRouteDisplayed()
 {
 return false;
 }
}


问:
AppleScript K750 Toggle Fn Keys
I'm new on AppleScript, and I'm trying to make a keyboard shortcut to toggle Fn Keys on my Logitech K750. I use AutoCAD and really need it.

I started to to try some codes, but till now no success... can anybody help me?

Here is the code...

Thank you!!!

tell application "Device Manager"
    activate
end tell
tell application "Device Manager"
    get every attribute of checkbox "When this box is checked, press F1, F2, etc. keys to use the standard function keys, and press and hold the Fn key to use the enhanced functions printed on the keys." of window "Wireless Solar Keyboard K750 for Mac"
    click checkbox "When this box is checked, press F1, F2, etc. keys to use the standard function keys, and press and hold the Fn key to use the enhanced functions printed on the keys." of window "Wireless Solar Keyboard K750 for Mac"
        activate
    if value of checkbox "When this box is checked, press F1, F2, etc. keys to use the standard function keys, and press and hold the Fn key to use the enhanced functions printed on the keys." of window "Wireless Solar Keyboard K750 for Mac" = 0 then
            display dialog "Standard Function Keys off..." giving up after 1
    else
        display dialog "Standard Function Keys on..." giving up after 1
    end if
end tell
tell application "Device Manager"
    quit
end tell

答:
I know this an old question, and this answer doesn't strictly address the question about AppleScript, but this thread was a top Google result for the general issue of toggling the Fn key on the Logitech K750 Solar Mac keyboard.

The solution I found for that general issue was to install the new-ish Logitech Options utility. Once that's installed and open, select the keyboard and toggle the checkbox next to Use all F1, F2, etc. keys as standard function keys to get your desired Fn key functionality.

Title: AppleScript K750 Toggle Fn Keys


问:
What's the best way to have multiple dockerfiles in one .NET solution?
Let's say I have multiple WebApi projects in one solution. There's also some common projects which are class libraries (core, data access), and all of those web apis have project references to those class libraries. I want to have a separate Dockerfile in each of those apis, but since they have those project references it becomes complicated. The way Microsoft solves this (when you enable docker support) is that they build the Dockerfile with the context set at the solution root level. The problem with that is that everything gets copied into the image, including the other api code. If you try to manually copy what you need then the paths get weird in terms of relativity to the dockerfile, since the context is set to the solution root level, not at the Dockerfile level. If you execute the build command at the Dockerfile level (the path where your Dockerfile is), then you don't have access to the outer referenced projects. There are some other workarounds with mounting the referenced projects as volumes but all of these approaches have some  drawbacks. So which solution would be the cleanest for this problem?</p>

答:
If you do a multistage build where you dotnet build the .csproj file for the webapi you want, then it doesn't matter that much that too much source code gets copied into the build stage.

Only the webapi and it's dependent projects will be built, so you'll only get what you need in the final image.


问:
Injecting code into Chrome pages
When I inject a JavaScript file using

```<code>"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["inject.js"]
    }
]
</code>```

in manifest.json, it doesn't inject it to Chrome pages, like chrome://extensions/.

Is there any solution for it?

答: Google doesn't allow extensions to work with certain URI like chrome://extensions/ for security and development reasons. See Can extensions modify chrome:// URLs?.

Title: Injecting code into Chrome pages

Body:
When I inject a JavaScript file using

"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["inject.js"]
    }
]

in manifest.json, it doesn't inject it to Chrome pages, like chrome://extensions/.

Is there any solution for it?


问:
Encapsulation of arrays, should I deep copy?
A class has a private array/list. It is encapsuled by only allowing editing through methods like "AddElement".

Now another class needs information about all elements of that array/list.

Passing the reference of the array/list would break the encapsulation. Returning a new array/list but with the same objects would still allow manipulating the objects. Creating a deep copy feels a bit like overkill. Is there a better way?

As an example:
In a game, I have multiple units. To put markers on a minimap, the unit's position and unit type is needed by the renderer. The renderer should not be able to change all kinds of properties of the units.

I'm doing this in C#.

答:
Create a new method which will expose only the needed info. Something like:</p>
```<code>public (Point Position, string UnitType) GetUnitInfo()
{
    return _units.Select(u => (u.Position, u.UnitType));
}
</code>```

Body:
Create a new method which will expose only the needed info. Something like:

public (Point Position, string UnitType) GetUnitInfo()
{
    return _units.Select(u => (u.Position, u.UnitType));
}


问:
Unable to use jsonpath function for output parameter in Argo Workflows
I've one workflow in which I'm using jsonpath function for a output parameter to extract a specific value from json string, but it is failing with this error Error (exit code 255)

Here is my workflow

```<code>apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: wf-dev-
spec:
  entrypoint: main
  templates:
    - name: main

      dag:
        tasks:
          - name: dev-create
            templateRef:
              name: dev-create-wft
              template: main
            arguments:
              parameters:
                - name: param1
                  value: "val1"

          - name: dev-outputs
            depends: dev-create.Succeeded
            templateRef:
              name: dev-outputs-wft
              template: main
            arguments:
              parameters:
                - name: devoutputs
                  value: "{{=jsonpath(tasks.dev-create.outputs.parameters.devoutputs, '$.alias.value')}}"
</code>```

In the above workflow task dev-create invokes another workflowTemplate dev-create-wft which returns the output of another workflowTemplate

Here is my workflowTemplate

```<code>apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: dev-create-wft

spec:
  entrypoint: main
  templates:
    - name: main
      outputs:
        parameters:
          - name: devoutputs
            valueFrom:
               expression: "tasks['dev1'].outputs.parameters.devoutputs"
      inputs:
        parameters:
          - name: param1
      dag:
        tasks:
          - name: dev1
            templateRef:
              name: fnl-dev
              template: main
            arguments:
              parameters:
                - name: param1
                  value: "{{inputs.parameters.param1}}"
</code>```

The returned json output looks like this

```<code>{
    "alias": {
        "value": "testing:dev1infra",
        "type": "string",
        "sensitive": false
    },
    "match": {
        "value": "dev1infra-testing",
        "type": "string",
        "sensitive": false
    }
}
</code>```

Does jsonpath function supported in workflow? The reason why am asking is, it's working when I used the same function in another workflowTemplate dev-outputs-wft

What could be the issue?

答:
When an expression fails to evaluate, Argo Workflows simply does not substitute the expression with its evaluated value. Argo Workflows passes the expression as if it were the parameter.

{{=}} "expression tag templates" in Argo Workflows must be written according to the expr language spec.

In simple tag templates, Argo Workflows itself does the interpreting. So hyphens in parameter names are allowed. For example, value: "{{inputs.parameters.what-it-is}}" is evaluated by Argo Workflows to be value: "over 9000!".

But in expression tag templates, expr interprets hyphens as minus operators. So value: "{{=inputs.parameters.what-it-is}}" looks like a really weird mathematical expression, fails, and isn't substituted. The workaround is to use ['what-it-is'] to access the appropriate map item.

My guess is that your expression is failing, Argo Workflows is passing the expression to dev-outputs-wft un-replaced, and whatever shell script is receiving that parameter is breaking.

If I'm right, the fix is easy:

```<code>           - name: dev-outputs
             depends: dev-create.Succeeded
             templateRef:
               name: dev-outputs-wft
               template: main
             arguments:
               parameters:
                 - name: devoutputs
-                   value: "{{=jsonpath(tasks.dev-create.outputs.parameters.devoutputs, '$.alias.value')}}"
+                   value: "{{=jsonpath(tasks['dev-create'].outputs.parameters.devoutputs, '$.alias.value')}}"
</code>```

Body:
I've one workflow in which I'm using jsonpath function for a output parameter to extract a specific value from json string, but it is failing with this error Error (exit code 255)

Here is my workflow

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: wf-dev-
spec:
  entrypoint: main
  templates:
    - name: main

      dag:
        tasks:
          - name: dev-create
            templateRef:
              name: dev-create-wft
              template: main
            arguments:
              parameters:
                - name: param1
                  value: "val1"

          - name: dev-outputs
            depends: dev-create.Succeeded
            templateRef:
              name: dev-outputs-wft
              template: main
            arguments:
              parameters:
                - name: devoutputs
                  value: "{{=jsonpath(tasks.dev-create.outputs.parameters.devoutputs, '$.alias.value')}}"

In the above workflow task dev-create invokes another workflowTemplate dev-create-wft which returns the output of another workflowTemplate

Here is my workflowTemplate

apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: dev-create-wft

spec:
  entrypoint: main
  templates:
    - name: main
      outputs:
        parameters:
          - name: devoutputs
            valueFrom:
               expression: "tasks['dev1'].outputs.parameters.devoutputs"
      inputs:
        parameters:
          - name: param1
      dag:
        tasks:
          - name: dev1
            templateRef:
              name: fnl-dev
              template: main
            arguments:
              parameters:
                - name: param1
                  value: "{{inputs.parameters.param1}}"

The returned json output looks like this

{
    "alias": {
        "value": "testing:dev1infra",
        "type": "string",
        "sensitive": false
    },
    "match": {
        "value": "dev1infra-testing",
        "type": "string",
        "sensitive": false
    }
}

Does jsonpath function supported in workflow? The reason why am asking is, it's working when I used the same function in another workflowTemplate dev-outputs-wft

What could be the issue?

Body:
When an expression fails to evaluate, Argo Workflows simply does not substitute the expression with its evaluated value. Argo Workflows passes the expression as if it were the parameter.

{{=}} "expression tag templates" in Argo Workflows must be written according to the expr language spec.

In simple tag templates, Argo Workflows itself does the interpreting. So hyphens in parameter names are allowed. For example, value: "{{inputs.parameters.what-it-is}}" is evaluated by Argo Workflows to be value: "over 9000!".

But in expression tag templates, expr interprets hyphens as minus operators. So value: "{{=inputs.parameters.what-it-is}}" looks like a really weird mathematical expression, fails, and isn't substituted. The workaround is to use ['what-it-is'] to access the appropriate map item.

My guess is that your expression is failing, Argo Workflows is passing the expression to dev-outputs-wft un-replaced, and whatever shell script is receiving that parameter is breaking.

If I'm right, the fix is easy:

           - name: dev-outputs
             depends: dev-create.Succeeded
             templateRef:
               name: dev-outputs-wft
               template: main
             arguments:
               parameters:
                 - name: devoutputs
-                   value: "{{=jsonpath(tasks.dev-create.outputs.parameters.devoutputs, '$.alias.value')}}"
+                   value: "{{=jsonpath(tasks['dev-create'].outputs.parameters.devoutputs, '$.alias.value')}}"


问:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component wehn trying to change data
I am learning React, in an app I'm trying to change description and amount and add a note, but every time I try I get an error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
```
<p>My code:</p>
```import React from "react";
import { useParams } from "react-router-dom";
import { connect } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

const navigate = useNavigate();

  return (

    <ExpenseForm
      expense ={props.expense}
       onSubmit={(expense) => {
        props.dispatch(editExpense(props.expense.id, expense))
          navigate('/')
         }}
       />

  )
}

const mapStateToProps = (state) => {
  const params = useParams()
  return {
     expense: state.expenses.find((expense) => expense.id === params.id)
  }
}

export default connect(mapStateToProps)(EditExpensePage)
```

答: As it is saying above, you can use a hook only inside a functional component. In your code you are calling useParams inside mapStateToProps that is not a functional component. I would suggest you not to use mapStateToProps as it is deprecated now and works only with class base components. I suggest you to use new syntax of react-redux that is completely based on hooks. You can learn its documentation here https://redux.js.org/</p>

Body:
I am learning React, in an app I'm trying to change description and amount and add a note, but every time I try I get an error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

My code:

import React from "react";
import { useParams } from "react-router-dom";
import { connect } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

const navigate = useNavigate();

  return (

    <ExpenseForm
      expense ={props.expense}
       onSubmit={(expense) => {
        props.dispatch(editExpense(props.expense.id, expense))
          navigate('/')
         }}
       />

  )
}

const mapStateToProps = (state) => {
  const params = useParams()
  return {
     expense: state.expenses.find((expense) => expense.id === params.id)
  }
}

export default connect(mapStateToProps)(EditExpensePage)


问:
Python/NumPy first occurrence of subarray
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

```<code>a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
</code>```

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

答:
Another try, but I'm sure there is more pythonic & efficent way to do that ...

```
def array_match(a, b):
    for i in xrange(0, len(a)-len(b)+1):
        if a[i:i+len(b)] == b:
            return i
    return None
```

```
a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

print array_match(a,b)
1
```

(This first answer was not in scope of the question, as cdhowie mentionned)

```<code>set(a) & set(b) == set(b)
</code>```

Body:
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

Body:
Another try, but I'm sure there is more pythonic & efficent way to do that ...

def array_match(a, b):
    for i in xrange(0, len(a)-len(b)+1):
        if a[i:i+len(b)] == b:
            return i
    return None

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

print array_match(a,b)
1

(This first answer was not in scope of the question, as cdhowie mentionned)

set(a) & set(b) == set(b)


问:
Ionic React send Object Prop to Child Component
I just dont get it. I am kinda new to Typescript but used to Code in React.js.
I have a simple Component like

```<code>const Tab1: React.FC = () => {

  const [spices, setSpices] = useState(
    [
      {
        Gewuerz: "pepper",
        Gramm: 50,
      },
      {
        Gewuerz: "Tumeric",
        Gramm: 870,
      },
      {
        Gewuerz: "salt",
        Gramm: 40,
      },
      {
        Gewuerz: "muscat",
        Gramm: 9,
      }
    ]);

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle class="ion-text-center">Spices</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <SpiceList spices={spices}/>
      </IonContent>

    </IonPage>

  );
};
</code>```

And a Child Component like

```<code>interface Props {
   spices: Object[];
 }

const SpiceList: React.FC<Props> = ({spices}: Props) => {

  return (

      <IonContent>
        <IonList>
          {spices.map((e) => <IonItem>{e.Gewuerz}</IonItem>)}
        </IonList>
      </IonContent>

  )

};

export default SpiceList;
</code>```

I want to render the different Spices inside Prop as a List. I can Map the Prop spices. But i cant access e.Gewuerz as it says it is not available inside of e. So how can i access the SubElements of spices?

EDIT: So it actually works like i tried it. But it always says "Compiled with Errors." If i dismiss it the app renders like i want it to.

答:
A vague type like object doesn't have any known properties, so Typescript won't let you access any properties on it.

Your spices are all of a specific type { Gewuerz: string; Gramm: number; } so you need to use that type in order to get any useful type information.

You can use that type as-is:

```<code>interface Props {
  spices: { Gewuerz: string; Gramm: number; }[];
}
</code>```

But you probably want to create a named type alias.  Especially if this Spice object is something that you use throughout your app.

```<code>interface Spice {
  Gewuerz: string;
  Gramm: number;
}

interface Props {
  spices: Spice[];
}
</code>```

Note that you do not need to use React.FC<Props> and ({spices}: Props).  You only need one or the other.

Body:
I just dont get it. I am kinda new to Typescript but used to Code in React.js.
I have a simple Component like

const Tab1: React.FC = () => {

  const [spices, setSpices] = useState(
    [
      {
        Gewuerz: "pepper",
        Gramm: 50,
      },
      {
        Gewuerz: "Tumeric",
        Gramm: 870,
      },
      {
        Gewuerz: "salt",
        Gramm: 40,
      },
      {
        Gewuerz: "muscat",
        Gramm: 9,
      }
    ]);

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle class="ion-text-center">Spices</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <SpiceList spices={spices}/>
      </IonContent>

    </IonPage>

  );
};

And a Child Component like

interface Props {
   spices: Object[];
 }

const SpiceList: React.FC<Props> = ({spices}: Props) => {

  return (

      <IonContent>
        <IonList>
          {spices.map((e) => <IonItem>{e.Gewuerz}</IonItem>)}
        </IonList>
      </IonContent>

  )

};

export default SpiceList;

I want to render the different Spices inside Prop as a List. I can Map the Prop spices. But i cant access e.Gewuerz as it says it is not available inside of e. So how can i access the SubElements of spices?

EDIT: So it actually works like i tried it. But it always says "Compiled with Errors." If i dismiss it the app renders like i want it to.

Body:
A vague type like object doesn't have any known properties, so Typescript won't let you access any properties on it.

Your spices are all of a specific type { Gewuerz: string; Gramm: number; } so you need to use that type in order to get any useful type information.

You can use that type as-is:

interface Props {
  spices: { Gewuerz: string; Gramm: number; }[];
}

But you probably want to create a named type alias.  Especially if this Spice object is something that you use throughout your app.

interface Spice {
  Gewuerz: string;
  Gramm: number;
}

interface Props {
  spices: Spice[];
}

Note that you do not need to use React.FC<Props> and ({spices}: Props).  You only need one or the other.


问:
Can I alter multiple illustrator ai-files to svg files and preserve the layers?
I have multiple .ai-files prepared in adobe illustrator CS3. I would like to transform all of these .ai-files in one go to .svg-files - but preserve the layering I originally had in the .ai-files?

I can easily open my .ai-files in Adobe Illustrator and export them individually from within Adobe Illustrator to an .svg-format. But this will take quite some time to do on more than one hundred .ai-files.

I have no issues opening an .ai-file from a .svg-file reading software, such as InkScape. But I can see that all the layers in the original .ai-files have been fused in to a single layer in InkScape.

I don't want to manually open every single .ai-file from within an .svg-reading software and manually pick and move elements to new layers. This will take an eternity to do on all my .ai-files.
Many of my .ai-files have quite a lot of layers.

I am pretty sure there isn't a question like this on StackFolder. The majority of the questions appear to go in the opposite direction from svg to ai files.
But please redirect me to a different post if I have overlooked something.

Thanks in advance for your help on this

答:
I know it doesn't make much sense to answer after over six years... But anyway. Here is the script that finds all AI files in selected folder and its subfolders and export them in SVG:</p>
```<code>main();

function main() {
    var folder = Folder.selectDialog('Select folder');
    if (!(folder instanceof Folder)) return;

    var files = get_ai_files(folder, []);
    if (files.length == 0) {
        alert('The folder contains no AI files')
        return;
    }

    for (var i = 0; i < files.length; i++) {
        var doc = app.open(files[i]);
        var file = File(doc.fullName.fsName.replace(/\.ai$/i, '.svg'))
        doc.exportFile(file, ExportType.SVG);
        doc.close(SaveOptions.DONOTSAVECHANGES);
    }

    alert('Number of saved SVG files: ' + files.length);
}

function get_ai_files(folder, files_array) {
    var files = folder.getFiles('*');
    if (files.length == 0) return files_array;
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (/.+\.ai$/i.test(file.name)) files_array.push(file);
        if (file instanceof Folder) files_array.concat(get_ai_files(file, files_array));
    }
    return files_array;
}
</code>```

Body:
I know it doesn't make much sense to answer after over six years... But anyway. Here is the script that finds all AI files in selected folder and its subfolders and export them in SVG:

main();

function main() {
    var folder = Folder.selectDialog('Select folder');
    if (!(folder instanceof Folder)) return;

    var files = get_ai_files(folder, []);
    if (files.length == 0) {
        alert('The folder contains no AI files')
        return;
    }

    for (var i = 0; i < files.length; i++) {
        var doc = app.open(files[i]);
        var file = File(doc.fullName.fsName.replace(/\.ai$/i, '.svg'))
        doc.exportFile(file, ExportType.SVG);
        doc.close(SaveOptions.DONOTSAVECHANGES);
    }

    alert('Number of saved SVG files: ' + files.length);
}

function get_ai_files(folder, files_array) {
    var files = folder.getFiles('*');
    if (files.length == 0) return files_array;
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (/.+\.ai$/i.test(file.name)) files_array.push(file);
        if (file instanceof Folder) files_array.concat(get_ai_files(file, files_array));
    }
    return files_array;
}


问:
Navigate to new page once upload is done
i'd like to naviagte to a new page to display the uploaded image , I've created custom function 'navigateToNewPage' to navigate , but I get this error

This expression has a type of 'void' so its value can't be used. Try
checking to see if you're using the correct API; there might be a
function or call that returns void you didn't expect. Also check type
parameters and variables which might also be void.

code :

```<code>  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Pick Image Camera"),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Card(
                child: (imageFile == null)
                    ? Text("Choose Image")
                    : navigateToNewPage() // here's the problem
,
              ),
              MaterialButton(
                textColor: Colors.white,
                color: Colors.pink,
                onPressed: () {
                  _showChoiceDialog(context);
                },
                child: Text("Select Image"),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _openGallery(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    setState(() {
      imageFile = pickedFile!;
    });

    Navigator.pop(context);
  }

  void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    setState(() {
      imageFile = pickedFile!;
    });
    Navigator.pop(context);
  }

  void navigateToNewPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => second()),
    );
  }
</code>```

答:
The error message tells you the problem:

"Card()" is expecting a widget argument for "child".

Your method, "navigateToNewPage()", is a void function - it doesn't return anything.

Change "navigateToNewPage()" to return a widget; or - better - modify your code so that your app simply goes to a new page as soon as you've picked a file.

PS:
Here's a tutorial - with some example code - that might help:

Flutter Image Picker : How to pick image from Gallery or Camera and Display it?

Body:
i'd like to naviagte to a new page to display the uploaded image , I've created custom function 'navigateToNewPage' to navigate , but I get this error

This expression has a type of 'void' so its value can't be used. Try
checking to see if you're using the correct API; there might be a
function or call that returns void you didn't expect. Also check type
parameters and variables which might also be void.

code :

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Pick Image Camera"),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Card(
                child: (imageFile == null)
                    ? Text("Choose Image")
                    : navigateToNewPage() // here's the problem
,
              ),
              MaterialButton(
                textColor: Colors.white,
                color: Colors.pink,
                onPressed: () {
                  _showChoiceDialog(context);
                },
                child: Text("Select Image"),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _openGallery(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    setState(() {
      imageFile = pickedFile!;
    });

    Navigator.pop(context);
  }

  void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    setState(() {
      imageFile = pickedFile!;
    });
    Navigator.pop(context);
  }

  void navigateToNewPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => second()),
    );
  }


问:
Mysql-Client Jumphost from Local Client to Webserver to DB Server without DB Server SSH User
My scenario looks as follows:

I have a web server and a DB server. On the webserver I have an SSH user with which I can connect to the database via mysql-client. The mysql port is restricted to the IP address of the webserver and I don't have an SSH user on the DB server.

I thought that some kind of SSH tunnel should be possible here, but I couldn't wrap my head around it yet.

I would have imagined something along these lines:

Tunnel: 127.0.0.1:9999 -> Webserver.IP:9999 -> DBserver.IP:3306

Mysql-Client CMD: mysql -u db_user -h 127.0.0.1 -p -P 9999

If anyone can share an idea on if and how this can be implemented I would be very grateful.

答:
I have found a solution that works for me..

Establish connection and keep it open:
ssh -L 9999:[DB-SERVER.IP]:3306 [SSH-USER]@[WEB-SERVER.IP]

Connect to the local source port:
mysql -h 127.0.0.1 -P 9999 -u [DB-USER] -p


问:
how to use for loop inside itemBuilder flutter
i am trying to use for loop inside itemBuilder to show inline ads, i have two ListView.separated one is list from data api and the second one from admob ads , my code is work fine and show the ads but it just show once because i used this line of code i want to convert it to for loop but i don't know how I just want to change this line of code

if (index == 10) { return _getAdWidget();}

i want to convert it to for loop and execute every 10 index please help

here is my code

```<code>Widget build(BuildContext context) {
return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: true,
        backgroundColor: Colors.black,
        title: Text("طرائف عن الحيوانات"),
        centerTitle: true,
      ),
      backgroundColor: Colors.grey[900],
      body: FutureBuilder(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            List snap = snapshot.data;

            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasError) {
              return Center(
                child: Text("error"),
              );
            }
            return ListView.separated(
              itemCount: snap.length,
              separatorBuilder: (context, index) {
                final data = snap[index];
                final dataJoke = data["joke"];
                final dataAnswer = data["answer"];

                return Card(
                  elevation: 6,
                  margin: EdgeInsets.all(10),
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("images/110.png"),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: ListTile(
                      title: Text(
                        " ${snap[index]['joke']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      subtitle: Text(
                        " ${snap[index]['answer']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.w600),
                      ),
                      trailing: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                            minimumSize: Size(1, 30),
                            primary: Colors.grey[900], // background
                            onPrimary: Colors.yellow,
                            elevation: 0),
                        onPressed: () async {
                          const urlPreview =
                              "https://www.youtube.com/watch?v=CNUBhb_cM6E";
                          await Share.share(
                              "$dataJoke \n $dataAnswer \n للمزيد من الطرائف\n$urlPreview");
                        },
                        child: Icon(Icons.share_outlined),
                      ),
                    ),
                  ),
                );
              },
              itemBuilder: (BuildContext context, int index) {
                if (index == 10) {
                  return _getAdWidget();
                }
</code>```

答:
it is just simple, try to change this line of code

```<code>if (index == 10) {
                  return _getAdWidget();
                }
</code>```

to

```<code>if (index % 10 == 5) {
                  return _getAdWidget();
                }
</code>```

Body:
i am trying to use for loop inside itemBuilder to show inline ads, i have two ListView.separated one is list from data api and the second one from admob ads , my code is work fine and show the ads but it just show once because i used this line of code i want to convert it to for loop but i don't know how I just want to change this line of code

if (index == 10) { return _getAdWidget();}

i want to convert it to for loop and execute every 10 index please help

here is my code

Widget build(BuildContext context) {
return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: true,
        backgroundColor: Colors.black,
        title: Text("طرائف عن الحيوانات"),
        centerTitle: true,
      ),
      backgroundColor: Colors.grey[900],
      body: FutureBuilder(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            List snap = snapshot.data;

            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasError) {
              return Center(
                child: Text("error"),
              );
            }
            return ListView.separated(
              itemCount: snap.length,
              separatorBuilder: (context, index) {
                final data = snap[index];
                final dataJoke = data["joke"];
                final dataAnswer = data["answer"];

                return Card(
                  elevation: 6,
                  margin: EdgeInsets.all(10),
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("images/110.png"),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: ListTile(
                      title: Text(
                        " ${snap[index]['joke']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      subtitle: Text(
                        " ${snap[index]['answer']}",
                        textDirection: TextDirection.rtl,
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.w600),
                      ),
                      trailing: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                            minimumSize: Size(1, 30),
                            primary: Colors.grey[900], // background
                            onPrimary: Colors.yellow,
                            elevation: 0),
                        onPressed: () async {
                          const urlPreview =
                              "https://www.youtube.com/watch?v=CNUBhb_cM6E";
                          await Share.share(
                              "$dataJoke \n $dataAnswer \n للمزيد من الطرائف\n$urlPreview");
                        },
                        child: Icon(Icons.share_outlined),
                      ),
                    ),
                  ),
                );
              },
              itemBuilder: (BuildContext context, int index) {
                if (index == 10) {
                  return _getAdWidget();
                }

Body:
it is just simple, try to change this line of code

if (index == 10) {
                  return _getAdWidget();
                }

to

if (index % 10 == 5) {
                  return _getAdWidget();
                }


问:
Matching multiple variables in different dataframes and return value in R
I have two data frames:

```<code>c1 <- c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2")
d1 <- c("2017", "2018", "2019", "2020", "2021", "2019", "2019", "2019", "2020", "2021")

dfx <- data.frame(c1,d1)
</code>```
```<code>c2 <- c("1", "1", "2")
ds <- c("2017", "2020", "2017")
de <- c("2018", "2021", "2018")

dfy <- data.frame(c2,ds,de)
</code>```

c1 and c2 are unique IDs and d1, ds, and de are dates. ds and de are start and end dates.

I'm looking for a way to identify if the dates in dfx overlaps within the duration (ds and de) in dfy. I want to do this by id. And if they overlap, return a value of 0 and if it doesn't, return value of 1 in dataframe dfy.

So, ideal output of dfy should be:

c2
ds
de
output

1
2017
2018
0

1
2020
2021
0

2
2017
2018
1

Any help will be appreciated! Especially if using dplyr.

答:
```<code># set as data.table
lapply(list(dfx, dfy), \(i) setDT(i))

# join
dfz <- dfx[dfy, on=.(c1=c2), allow.cartesian=T]

# flag if overlap
dfz[, output := 1
    ][ d1 >= ds
       & d1 <= de
       , output := 0
       ]

# aggregate
dfz <- dfz[, .(output = min(output)), .(c1, ds, de)]
dfz
   c1   ds   de output
1:  1 2017 2018      0
2:  1 2020 2021      0
3:  2 2017 2018      1
</code>```

Body:
I have two data frames:

c1 <- c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2")
d1 <- c("2017", "2018", "2019", "2020", "2021", "2019", "2019", "2019", "2020", "2021")

dfx <- data.frame(c1,d1)

c2 <- c("1", "1", "2")
ds <- c("2017", "2020", "2017")
de <- c("2018", "2021", "2018")

dfy <- data.frame(c2,ds,de)

c1 and c2 are unique IDs and d1, ds, and de are dates. ds and de are start and end dates.

I'm looking for a way to identify if the dates in dfx overlaps within the duration (ds and de) in dfy. I want to do this by id. And if they overlap, return a value of 0 and if it doesn't, return value of 1 in dataframe dfy.

So, ideal output of dfy should be:

c2
ds
de
output

1
2017
2018
0

1
2020
2021
0

2
2017
2018
1

Any help will be appreciated! Especially if using dplyr.


问:
Subversion via Coda - What does commit mean?
Im using subversion via Coda on a Mac, and I have just set up my first site and following online tutorials I set my svn repository using command line at the terminal.

However when I go to my site, I see my files for the site on my local side, with either a question mark which says 'add file' when I hover over it and when I click that a green circle with a white 'A' saying 'commit this file'? when I hover over it. What does all this this mean?

Im new to this so please forgive me.

答:
When using Coda the easiest way is to click sites and create a new site for your project. Note there is a form for completing your SVN at the bottom.

However, what you are seeing is A meaning that your files have been added and are ready to be committed to svn. Typically in Coda you'd do this by selecting the added files and right clicking commit.

There is a wealth of information in general about SVN available here : http://svnbook.red-bean.com/nightly/en/index.html

Coda's SVN client is one of the many flavors of GUI's that make it easy for you to see what you are doing in a very visual way but it all usually is based on the same principle.

edit:
 Just to elaborate slightly; the actual reason you are being asked to commit is that Coda is asking you to make the decision whether you want the working copy (your local copy) to send changes to the repository (where you are storing your files).

Each commit creates a revision that allows you to look back through each individual commit and see what was changed and when. This will provide useful in future for finding errors or comparing files.


问:
Asp.net 4.8 MVC + Vite + Svelte + HMR?
I have a legacy application built in ASP.NET 4.8 MVC.
I would like to start building some client side features in Svelte - having svelte components rendering inside razor views. This I have working. I can render a svelte component anywhere in the razor page.
However vite has some problem (im guessing with HMR?), and it keeps refreshing the razor page (https://localhost:44300/somefeature) every few seconds.

Environment

asp.net 4.8 mvc loads to https://localhost:44300/

vite is loading on http://localhost:3000/

Here is what i have so far. I ran npm init vite@latest -> selected svelte + svelte TS

vite.config.js

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    svelte({
      compilerOptions: {
        customElement: true,
      }
    })
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: '/src/main.ts'
    }
  }
})```
</div>
</div>
</p>
<p>Then i followed the instructions here https://vitejs.dev/guide/backend-integration.html and added this to the razor page:</p>
```@Html.Raw("")

```

(Note - had to use Html.Raw because it wouldnt let me escape the @ correctly - even with @@)

At this point it is rendering my Svelte component perfectly.

The issue however is that vite is now reloading my page every 2 seconds or so - im guessing because HMR is no longer working correctly as the console just says: [vite] connecting...

Can anyone point me in a direction either to get HMR working whilst using another Backend server? For some reason it works in asp.net core, but not so in ASP.NET 4.8. Any observations to help?

Thanks in advance!

答:
Ok i got it working. Here is my vite.config.js. Pay special attention to the
input, outDir and server nodes, and adjust them to your scenario. The proxy is important, you can either set it to your https or http mvc endpoint and port that asp.net spins up for you.

Here is the config:

```<code>export default defineConfig({
  plugins: [
    svelte()
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: 'Scripts/svelte/app.js',
    },
    outDir: 'Scripts/svelte/dist'
  },
  server: {
    proxy:{
      '*' : {
        target: 'http://localhost:26688',
        changeOrigin: true
      }
    },
    hmr: {
      protocol: 'ws'
    }
  }
})

</code>```

Its pretty cool - you get instant HMR of any svelte component inside a razor page without losing any razor state.

Title: Asp.net 4.8 MVC + Vite + Svelte + HMR?

Body:
I have a legacy application built in ASP.NET 4.8 MVC.
I would like to start building some client side features in Svelte - having svelte components rendering inside razor views. This I have working. I can render a svelte component anywhere in the razor page.
However vite has some problem (im guessing with HMR?), and it keeps refreshing the razor page (https://localhost:44300/somefeature) every few seconds.

Environment

asp.net 4.8 mvc loads to https://localhost:44300/

vite is loading on http://localhost:3000/

Here is what i have so far. I ran npm init vite@latest -> selected svelte + svelte TS

vite.config.js

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    svelte({
      compilerOptions: {
        customElement: true,
      }
    })
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: '/src/main.ts'
    }
  }
})

Then i followed the instructions here https://vitejs.dev/guide/backend-integration.html and added this to the razor page:

@Html.Raw("")

(Note - had to use Html.Raw because it wouldnt let me escape the @ correctly - even with @@)

At this point it is rendering my Svelte component perfectly.

The issue however is that vite is now reloading my page every 2 seconds or so - im guessing because HMR is no longer working correctly as the console just says: [vite] connecting...

Can anyone point me in a direction either to get HMR working whilst using another Backend server? For some reason it works in asp.net core, but not so in ASP.NET 4.8. Any observations to help?

Thanks in advance!

Body:
Ok i got it working. Here is my vite.config.js. Pay special attention to the
input, outDir and server nodes, and adjust them to your scenario. The proxy is important, you can either set it to your https or http mvc endpoint and port that asp.net spins up for you.

Here is the config:

export default defineConfig({
  plugins: [
    svelte()
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: 'Scripts/svelte/app.js',
    },
    outDir: 'Scripts/svelte/dist'
  },
  server: {
    proxy:{
      '*' : {
        target: 'http://localhost:26688',
        changeOrigin: true
      }
    },
    hmr: {
      protocol: 'ws'
    }
  }
})

Its pretty cool - you get instant HMR of any svelte component inside a razor page without losing any razor state.


问:
Create dictionary where values are keys transformed to strings
G is a graph object and sorted(G) returns a list of nodes:

```<code>[0,1,2...1860]
</code>```

I need to rename those nodes mapping from a dictionary, like so:

```<code>mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}
</code>```

And then I can apply dict to a method that relabels my graph:

```<code>import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)
</code>```

and sorted(Gnew)returns:

```<code>[0_cereb, 2_cereb, ..., 1860_cereb]
</code>```

How do I create this mapping dict?

答:
Use a dictionary comprehension to create the dictionary, and use string formatting to convert the numbers to the corresponding strings.</p>
```<code>mapping = {x: f'{x}_cereb' for x in G}
</code>```

Body:
G is a graph object and sorted(G) returns a list of nodes:

[0,1,2...1860]

I need to rename those nodes mapping from a dictionary, like so:

mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}

And then I can apply dict to a method that relabels my graph:

import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)

and sorted(Gnew)returns:

[0_cereb, 2_cereb, ..., 1860_cereb]

How do I create this mapping dict?

Body:
Use a dictionary comprehension to create the dictionary, and use string formatting to convert the numbers to the corresponding strings.

mapping = {x: f'{x}_cereb' for x in G}