问:
C# .NET communicate between computers over network
How should I go about making an application with C# and .NET where, say, on one computer a button is pressed that triggers an event on the other?

I saw this:

Recommended way to communicate between processes running on different computers on the same network

I've never heard of WCF, is that what I should try?

答:
You're question is way to broad however I can give you a brief overview of how WCF (and most client/server apps) work.

You create a WCF service and then you reference the WCF service (in VS right click references then add service reference) inside your client application. The click in the client application will send a message to the WCF service that will deal with that message.

As mentioned the getting started guides are pretty decent. The WCF Test Client is a great debugging tool as well. If you open the Visual Studio command prompt and type wcftestclient, it will pop up.

Here are some articles that might be helpful:

http://msdn.microsoft.com/en-us/netframework/aa663324.aspx

http://msdn.microsoft.com/en-us/library/dd936243.aspx

http://msdn.microsoft.com/en-us/library/aa751792.aspx

http://blogs.msdn.com/b/tess/archive/2009/01/09/net-hang-my-application-hangs-after-i-called-my-wcf-service-a-couple-of-times.aspx

http://blogs.msdn.com/b/wenlong/archive/2009/07/26/wcf-4-higher-default-throttling-settings-for-wcf-services.aspx

http://merill.net/2008/10/wcf-performance-optimization-tips/


来源: stackexchange

问:
AWS S3: How to retrieve bucket activities?
I have a project based on Nest.js, TypeScript, and Kubernetes.

In my project, I need to handle updates in the AWS S3 bucket, like Publishing of new files, Updating files, and Deleting as well, and do something with that information.

I know about the streams, which can trigger the Lambda functions on S3 bucket events(PutObject, Update, Delete, and so on). I want to find a way, to implement the same thing without lambda functions if it is possible.

As an alternative way, that logic can be implemented by the Cron job, which should get the objects from the bucket, and process them. But for that case, I need to compare data to define what is happened.

I also think about the case to have Lambda functions, which should handle the S3 bucket streams, and send the request to the needed APIs.

So, is anybody faced with the same case? If so, how do you solved it?
Is it possible to have an S3 webhook directly to API, if so how?

I will be grateful for the suggestions!

Thanks!

答:
After the research, I found that it can be done using the MinIO

It is a good way to implement it with the RabbitMQ, and handle events from the AWS S3 Bucket

Here are some useful guidelines

https://docs.min.io/docs/minio-bucket-notification-guide.html

http://nm-muzi.com/docs/minio-bucket-notification-guide.html

MinIO in DockerHub

ContentLicense: CC BY-SA 4.0


问:
Conversions in C++ program
Please see the image below for this complex problem:

After reading that: So far I have a lot of the code written up. I just dont know quite how to add together the pounds, shellings, and pence because of the conversions. I think I may have been able to add up the pounds and shellings properly, but I'm going crazy over trying to find a way to add up the shellings, while keeping conversions and format proper! Please help!

```<code>/*Write a program that asks the user to enter two money amounts expressed in old-pounds and will then add the two amounts and display the answer both in old-pounds and in decimal-pounds.
OLD CURRENCY
1 pound= 20 shillings
1 pound=240 pence
1 shilling= 12 pence
conversion rate from old pence to new pence *.416
*/

#include <iostream>
using namespace std;

int main()
{
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    int pounds=0;
    int shillings=0;
    int pence=0;
    char dot1;
    char dot2;
    int pounds2=0;
    int shillings2=0;
    int pence2=0;
    char dot12=0;
    char dot22=0;
    double Poundtotal=0;
    int shillingstotal=0;
    int pencetotal=0;
    double x;
    double y;

    cout << "Enter first old-pound amount:";
    cin >> pounds >> dot1 >> shillings >> dot2 >> pence;
    cout << "Enter second old-pound amount:";
    cin >> pounds2 >> dot12 >> shillings2 >> dot22 >> pence2;
    Poundtotal= (pounds+pounds2);
    shillingstotal=(shillings+shillings2);
    pencetotal=pence+pence2;
    x=(shillingstotal*12)+pencetotal;
    while (x>240)
    {
        Poundtotal=Poundtotal+1;
        x=x-240;
    }

    cout<<x<<endl;
    cout<<Poundtotal<<endl;

    /*need to find a way to add the rest!*/

    return 0;
}
</code>```

答:
Posting an answer to help others who might be stumped with the same or similar question.
You can chain the inputs collected through cin. You can modify this code to add the old pound.</p>
```<code>#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    cout << "Enter the amount in pound-shillings-pence format (e.g. 5.2.8): ";
    int pounds, shillings, pence;
    char separator;
    cin >> pounds >> separator >> shillings >> separator >> pence;

    //Imperial pound to imperial pence (1 pound = 240 pence)
    pence += 240 * pounds;
    //Imperial shilling to pence (1 Shilling = 12 pence)
    pence += 12 * shillings;
    //Decimal pounds
    //Unicode for the pound sign = \u00A3
    cout << "Decimal pounds: \u00A3" << fixed << setprecision(2) << (float) pence/240 << endl;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Conversions in C++ program

Body:
Please see the image below for this complex problem:

After reading that: So far I have a lot of the code written up. I just dont know quite how to add together the pounds, shellings, and pence because of the conversions. I think I may have been able to add up the pounds and shellings properly, but I'm going crazy over trying to find a way to add up the shellings, while keeping conversions and format proper! Please help!

/*Write a program that asks the user to enter two money amounts expressed in old-pounds and will then add the two amounts and display the answer both in old-pounds and in decimal-pounds.
OLD CURRENCY
1 pound= 20 shillings
1 pound=240 pence
1 shilling= 12 pence
conversion rate from old pence to new pence *.416
*/

#include <iostream>
using namespace std;

int main()
{
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    int pounds=0;
    int shillings=0;
    int pence=0;
    char dot1;
    char dot2;
    int pounds2=0;
    int shillings2=0;
    int pence2=0;
    char dot12=0;
    char dot22=0;
    double Poundtotal=0;
    int shillingstotal=0;
    int pencetotal=0;
    double x;
    double y;

    cout << "Enter first old-pound amount:";
    cin >> pounds >> dot1 >> shillings >> dot2 >> pence;
    cout << "Enter second old-pound amount:";
    cin >> pounds2 >> dot12 >> shillings2 >> dot22 >> pence2;
    Poundtotal= (pounds+pounds2);
    shillingstotal=(shillings+shillings2);
    pencetotal=pence+pence2;
    x=(shillingstotal*12)+pencetotal;
    while (x>240)
    {
        Poundtotal=Poundtotal+1;
        x=x-240;
    }

    cout<<x<<endl;
    cout<<Poundtotal<<endl;

    /*need to find a way to add the rest!*/

    return 0;
}

Body:
Posting an answer to help others who might be stumped with the same or similar question.
You can chain the inputs collected through cin. You can modify this code to add the old pound.

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    cout << "Enter the amount in pound-shillings-pence format (e.g. 5.2.8): ";
    int pounds, shillings, pence;
    char separator;
    cin >> pounds >> separator >> shillings >> separator >> pence;

    //Imperial pound to imperial pence (1 pound = 240 pence)
    pence += 240 * pounds;
    //Imperial shilling to pence (1 Shilling = 12 pence)
    pence += 12 * shillings;
    //Decimal pounds
    //Unicode for the pound sign = \u00A3
    cout << "Decimal pounds: \u00A3" << fixed << setprecision(2) << (float) pence/240 << endl;
}


问:
How do I get rid of an error when trying to scrape a site?
When I try to scrape woolworths for grocery price data, I get the following error: urllib.error.HTTPError: HTTP Error 403: Forbidden

Here's what my code looks like:

```<code>    session = requests.session()
url = "https://www.woolworths.com.au/shop/browse/fruit-veg"
headers = {"User-Agent":"Mozilla/5.0"}
req = session.get(url, headers = headers)
fruitAndVeg = BeautifulSoup(req.text)
</code>```

I searched it up and changed my headers, but it still isn't working after that.

答:
Try using a complete user-agent such as

```<code>headers = {"User-Agent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/96.0 Mobile/15E148 Safari/605.1.15"}
</code>```

Additionally, it may so happen that some websites in the loop might not be simply available, to cater to it. You must catch the statement in a python exception to prevent breaking the code.

If this does not work, try using rotating proxy by using a more robust scrapping platform Scrapy
How to rotate proxies and user agents

Body:
When I try to scrape woolworths for grocery price data, I get the following error: urllib.error.HTTPError: HTTP Error 403: Forbidden

Here's what my code looks like:

    session = requests.session()
url = "https://www.woolworths.com.au/shop/browse/fruit-veg"
headers = {"User-Agent":"Mozilla/5.0"}
req = session.get(url, headers = headers)
fruitAndVeg = BeautifulSoup(req.text)

I searched it up and changed my headers, but it still isn't working after that.

Body:
Try using a complete user-agent such as

headers = {"User-Agent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/96.0 Mobile/15E148 Safari/605.1.15"}

Additionally, it may so happen that some websites in the loop might not be simply available, to cater to it. You must catch the statement in a python exception to prevent breaking the code.

If this does not work, try using rotating proxy by using a more robust scrapping platform Scrapy
How to rotate proxies and user agents


问:
Artifactory configuring Tomcat server for SSL
I am a newbie to Artifactory and I have installed the OSS ver. 7.31.13 build of Artifactory from repo as outlined in Artifactory install guide. I'm trying to configure the bundled Tomcat server for SSL by using the config options in the system.yaml file.  Here is what I am setting in the system.yaml file:

```<code>httpsConnector:
        ## Enable connector with SSL/TLS
        enabled: true
        ## Port to use for the HTTPS connector
        port: 8443
        ## Certificate file to use
        #certificateFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/jfa.cer"
        certificateFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/server.crt"
        ## Certificate key file to use.
        #certificateKeyFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/jfa.key"
        certificateKeyFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/server.key"
        ## Extra configuration for the HTTPS connector.
        ## For example extraConfig: "SSLProtocol='TLSv1+TLSv1.1+TLSv1.2'"
        extraConfig: "SSLProtocol='TLSv1.2'"
</code>```

I have wanted to add more extra options, i.e. Ciphers to use and to "honor" the order of the Cipher listed.  But right now I'm just trying to get SSL working.  At one point, ports 8081 and 8082 disappeared along with no reference to port 8443 and/or the certificate and private key showing in any log files, even the catalina files that are generated for Tomcat.  When I "pared" back on the configuration, i.e. only specifiying SSLProtocol only, I was able to get ports 8081 and 8082 to show again, but still no port 8443.  I've also specified a different certificate and key file by copying my certificate and private key to new names, thinking that these names need to match what is in the template file.  This configuration seems relatively straight forward, but its like I'm missing something.
Any assistance you are able to provide would be most appreciated.

Thanks,

Eric. :)

答:
See the following article from JFrog about custom certificates and follow the steps in there.
Please pay special attention to the section Custom Certificate and CA Prerequisites and validate your certificate following the prerequisites.

If you wish to debug the issue, you can check out for warning\errors on the following logs

```<code>$JFROG_HOME/artifactory/var/artifactory/log/router-service.log
$JFROG_HOME/artifactory/var/artifactory/log/access-service.log
</code>```

Body:
I am a newbie to Artifactory and I have installed the OSS ver. 7.31.13 build of Artifactory from repo as outlined in Artifactory install guide. I'm trying to configure the bundled Tomcat server for SSL by using the config options in the system.yaml file.  Here is what I am setting in the system.yaml file:

httpsConnector:
        ## Enable connector with SSL/TLS
        enabled: true
        ## Port to use for the HTTPS connector
        port: 8443
        ## Certificate file to use
        #certificateFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/jfa.cer"
        certificateFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/server.crt"
        ## Certificate key file to use.
        #certificateKeyFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/jfa.key"
        certificateKeyFile: "/opt/jfrog/artifactory/var/etc/artifactory/security/ssl/server.key"
        ## Extra configuration for the HTTPS connector.
        ## For example extraConfig: "SSLProtocol='TLSv1+TLSv1.1+TLSv1.2'"
        extraConfig: "SSLProtocol='TLSv1.2'"

I have wanted to add more extra options, i.e. Ciphers to use and to "honor" the order of the Cipher listed.  But right now I'm just trying to get SSL working.  At one point, ports 8081 and 8082 disappeared along with no reference to port 8443 and/or the certificate and private key showing in any log files, even the catalina files that are generated for Tomcat.  When I "pared" back on the configuration, i.e. only specifiying SSLProtocol only, I was able to get ports 8081 and 8082 to show again, but still no port 8443.  I've also specified a different certificate and key file by copying my certificate and private key to new names, thinking that these names need to match what is in the template file.  This configuration seems relatively straight forward, but its like I'm missing something.
Any assistance you are able to provide would be most appreciated.

Thanks,

Eric. :)

Body:
See the following article from JFrog about custom certificates and follow the steps in there.
Please pay special attention to the section Custom Certificate and CA Prerequisites and validate your certificate following the prerequisites.

If you wish to debug the issue, you can check out for warning\errors on the following logs

$JFROG_HOME/artifactory/var/artifactory/log/router-service.log
$JFROG_HOME/artifactory/var/artifactory/log/access-service.log


问:
How to print a string while a download is happening?
I want Python to print out strings while a process is happening, such as the download in the script below. However, I'm finding it difficult. For example, maybe I want Python to say after 10 seconds of download, "Hey, it's been 10 secs." I can put the start time only before the process, and the end time only after the process, which means I can't track while the download is happening.</p>
```<code>import requests, re, time

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/realdonaldtrump/status&matchType=prefix&filter=statuscode:200"

response = requests.head(link).text
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', response)
for url in urls:
    start = time.time()
    data2.append(f"{url}")
    end = time.time()
    time_elapsed = end - start
    if time_elapsed >= 10:
        print("It's been 10 seconds.")
</code>```

答:
you can use progress bar:

use progressbar module

```<code>import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
    bar.update(i+1)
    sleep(0.1)
bar.finish()
</code>```

```<code>def print_progress_bar(total, current, barsize=60):
    progress = int(current*barsize/total)
    completed = str(int(current*100/total)) + '%'
    print('[', chr(9608)*progress, ' ', completed, '.'*(barsize-progress), '] ', str(i)+'/'+str(total), sep='', end='\r', flush=True)
</code>```

example:

```<code>total = 6000
barsize = 60
print_frequency = max(min(total//barsize, 100), 1)
print("Start Task..", flush=True)
for i in range(1, total+1):
  if i%print_frequency == 0 or i == 1:
    print_progress_bar(total, i, barsize)
print("\nFinished", flush=True)
</code>```

Body:
I want Python to print out strings while a process is happening, such as the download in the script below. However, I'm finding it difficult. For example, maybe I want Python to say after 10 seconds of download, "Hey, it's been 10 secs." I can put the start time only before the process, and the end time only after the process, which means I can't track while the download is happening.

import requests, re, time

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/realdonaldtrump/status&matchType=prefix&filter=statuscode:200"

response = requests.head(link).text
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', response)
for url in urls:
    start = time.time()
    data2.append(f"{url}")
    end = time.time()
    time_elapsed = end - start
    if time_elapsed >= 10:
        print("It's been 10 seconds.")

Body:
you can use progress bar:

use progressbar module

import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
    bar.update(i+1)
    sleep(0.1)
bar.finish()

def print_progress_bar(total, current, barsize=60):
    progress = int(current*barsize/total)
    completed = str(int(current*100/total)) + '%'
    print('[', chr(9608)*progress, ' ', completed, '.'*(barsize-progress), '] ', str(i)+'/'+str(total), sep='', end='\r', flush=True)

example:

total = 6000
barsize = 60
print_frequency = max(min(total//barsize, 100), 1)
print("Start Task..", flush=True)
for i in range(1, total+1):
  if i%print_frequency == 0 or i == 1:
    print_progress_bar(total, i, barsize)
print("\nFinished", flush=True)


问:
InitializationError while running Cucumber JUnit Tests
```<code>package cucumber;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format={"pretty"},
        features= "src/features/"
        )
public class cucumberRunner {

}
</code>```

Using:

cucumber-core-1.2.4

cucumber-java-1.2.4

cucumber-junit-1.2.4

junit-4.12

Eclipse Mars.1

java 8

Error Trace:

java.lang.NoClassDefFoundError: org/dom4j/Element
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetPublicMethods(Unknown Source)
        at java.lang.Class.getMethods(Unknown Source)
        at cucumber.runtime.java.MethodScanner.scan(MethodScanner.java:40)
        at cucumber.runtime.java.JavaBackend.loadGlue(JavaBackend.java:86)
        at cucumber.runtime.Runtime.(Runtime.java:91)
        at cucumber.runtime.Runtime.(Runtime.java:69)
        at cucumber.runtime.Runtime.(Runtime.java:65)
        at cucumber.api.junit.Cucumber.createRuntime(Cucumber.java:78)
        at cucumber.api.junit.Cucumber.(Cucumber.java:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
        at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
      Caused by: java.lang.ClassNotFoundException: org.dom4j.Element
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 28 more

What could be the problem?

答:
On your testRunner, make sure you import the correct Junit libraries. Once you hover your mouse on the @RunWith(Cucumber.class), eclipse will provide you with two options, make sure NOT to select "Add JUnit 4 Library to build path".

However, select import 'RunWith'(org.junit.runner) and import it. This will solve the error.

Body:
package cucumber;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format={"pretty"},
        features= "src/features/"
        )
public class cucumberRunner {

}

Using:

cucumber-core-1.2.4

cucumber-java-1.2.4

cucumber-junit-1.2.4

junit-4.12

Eclipse Mars.1

java 8

Error Trace:

java.lang.NoClassDefFoundError: org/dom4j/Element
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetPublicMethods(Unknown Source)
        at java.lang.Class.getMethods(Unknown Source)
        at cucumber.runtime.java.MethodScanner.scan(MethodScanner.java:40)
        at cucumber.runtime.java.JavaBackend.loadGlue(JavaBackend.java:86)
        at cucumber.runtime.Runtime.(Runtime.java:91)
        at cucumber.runtime.Runtime.(Runtime.java:69)
        at cucumber.runtime.Runtime.(Runtime.java:65)
        at cucumber.api.junit.Cucumber.createRuntime(Cucumber.java:78)
        at cucumber.api.junit.Cucumber.(Cucumber.java:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
        at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
      Caused by: java.lang.ClassNotFoundException: org.dom4j.Element
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 28 more

What could be the problem?


问:
Astoria vs. SQL Server Data Services
What are in your opinion big differences between areas of usage for "Astoria" (ADO.NET data services) and SQL Server Data Services?</p>

答:
They are similiar but very different technologies. Astoria or what is now called at Microsoft ADO.NET Data Services is a programming library that will allow data to be passed through RESTful web services.  You develop these web services to be run against data you have access to.  ADO.NET Data Services is now included in the .NET 3.5 SP1 updates.

SQL Server Data Services is a new service provided by Microsoft.  The following is a decription:

"SQL Server Data Services (SSDS) are highly scalable, on-demand data
  storage and query processing utility
  services. Built on robust SQL Server
  database and Windows Server
  technologies, these services provide
  high availability, security and
  support standards-based web interfaces
  for easy programming and quick
  provisioning."

SQL Server Data Services is very similair to Amazon S3 service.

OwnerDisplayName: dimarzionist

ContentLicense: CC BY-SA 2.5

Title: Astoria vs. SQL Server Data Services

OwnerDisplayName: Chris Woodruff


问:
Determining if an Object is of primitive type
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:

```<code>int i = 3;
Object o = i;

System.out.println(o.getClass().getName() + ", " +
                   o.getClass().isPrimitive());
</code>```

prints java.lang.Integer, false.

Is there a right way or some alternative?

答:
The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example

```<code>System.out.println(Integer.class.isPrimitive());
</code>```

prints "false", but

```<code>public static void main (String args[]) throws Exception
{
    Method m = Junk.class.getMethod( "a",null);
    System.out.println( m.getReturnType().isPrimitive());
}

public static int a()
{
    return 1;
}
</code>```

prints "true"

Body:
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:

int i = 3;
Object o = i;

System.out.println(o.getClass().getName() + ", " +
                   o.getClass().isPrimitive());

prints java.lang.Integer, false.

Is there a right way or some alternative?

Body:
The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example

System.out.println(Integer.class.isPrimitive());

prints "false", but

public static void main (String args[]) throws Exception
{
    Method m = Junk.class.getMethod( "a",null);
    System.out.println( m.getReturnType().isPrimitive());
}

public static int a()
{
    return 1;
}

prints "true"

OwnerDisplayName: Steve B.


问:
How execute script from command prompt in python
I have mysql dump command that I would like to run from from windows shell
or command prompt. I have used shell it does work.

```<code>  d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql"
  fn = dn+d
  cmd="""mysqldump -u hapopdy -p   > %s""" %fn
  print cmd
</code>```

Edit:::::::
The -p needs to be a raw input.

答:
Using the subprocess module

```<code>import subprocess
subprocess.call(cmd)
</code>```

If you're running a shell command add shell=True

```<code>subprocess.call(cmd, shell=True)
</code>```

Body:
I have mysql dump command that I would like to run from from windows shell
or command prompt. I have used shell it does work.

  d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql"
  fn = dn+d
  cmd="""mysqldump -u hapopdy -p   > %s""" %fn
  print cmd

Edit:::::::
The -p needs to be a raw input.

Body:
Using the subprocess module

import subprocess
subprocess.call(cmd)

If you're running a shell command add shell=True

subprocess.call(cmd, shell=True)


问:
Filtering a JSON array in a Python JSON reading and parsing program
I am writing a python program that reads, parses, and hopefully filters out results in a JSON file coming from a URL. I have searched and watched videos for methods that could filter out specific results from a JSON file. However, this JSON file seems a little bit complicated.

```<code> {
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [ (different galaxies with their data etc.)
</code>```

The JSON file's content is too long, and I am trying to filter out the galaxies with a specific title such as Sombrero. Since each father array has so many children, how would I implement it? I have tried doing the following:

```<code>from urllib.request import urlopen
import json

url = "https://images-api.nasa.gov/search?q=galaxy&page=1"

response = urlopen(url)
data_json = json.loads(response.read())

list(list(filter(lambda x:x["title"]=="Sombrero", data_json)))
</code>```

答:
You can use list comprehension:

```<code>planets = [i for i in data_json['collection']['items'] if i['data'][0]['title'] == 'Andromeda Galaxy']
</code>```

To filter for partial string matches:

```<code>planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
</code>```

To filter for partial string matches regardless capitalization:

```<code>planets = [i for i in data_json['collection']['items'] if lower('Andromeda') in lower(i['data'][0]['title'])]
</code>```

Body:
I am writing a python program that reads, parses, and hopefully filters out results in a JSON file coming from a URL. I have searched and watched videos for methods that could filter out specific results from a JSON file. However, this JSON file seems a little bit complicated.

 {
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [ (different galaxies with their data etc.)

The JSON file's content is too long, and I am trying to filter out the galaxies with a specific title such as Sombrero. Since each father array has so many children, how would I implement it? I have tried doing the following:

from urllib.request import urlopen
import json

url = "https://images-api.nasa.gov/search?q=galaxy&page=1"

response = urlopen(url)
data_json = json.loads(response.read())

list(list(filter(lambda x:x["title"]=="Sombrero", data_json)))

Body:
You can use list comprehension:

planets = [i for i in data_json['collection']['items'] if i['data'][0]['title'] == 'Andromeda Galaxy']

To filter for partial string matches:

planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]

To filter for partial string matches regardless capitalization:

planets = [i for i in data_json['collection']['items'] if lower('Andromeda') in lower(i['data'][0]['title'])]


问:
Multiply string - [Leetcode] Problem with Java
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

```<code>class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}
</code>```

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.

答:
A Long is stored on 64 bits, with a maximum capacity of 2^63 - 1 (9.223372e+18)
so you are out of range. I suggest that you are pushing your test too far.
You could have changed to BigInteger if it were not proscribed, or to float, but for the purpose of your question assume that it's ok that these numbers are out range.
If you want you could check that the inputs are below 10^9 and throw an out of range error.</p>

Body:
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.


问:
jsconfig.json gives ts errors
I am having jsconfig.json in my root directory using Nuxt.js project.
And I am having an error:

```<code>File '/home/mike/Documents/nuxt/node_modules/dotenv/types' not found.
  The file is in the program because:
    Root file specified for compilation
</code>```

Actually 5 errors in a first line of jsconfig.json:

I don't even use typescript and I didn't set any typescript options while creating Nuxt.js project

jsconfig.json content:

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"],
      "~~/*": ["./*"],
      "@@/*": ["./*"]
    }
  },
  "exclude": ["node_modules", ".nuxt", "dist"]
}
</code>```

I don't understand where they come from.
How do I get rid of this errors?
There's no option quick fix so I can't ignore errors for entire file

答:
In my case the problem was that the project is in a subfolder inside monorepo.

So the solution was changing it into add ./ before node_modules:

```<code>"exclude": ["./node_modules", ".nuxt", "dist"],
</code>```

Title: jsconfig.json gives ts errors

Body:
I am having jsconfig.json in my root directory using Nuxt.js project.
And I am having an error:

File '/home/mike/Documents/nuxt/node_modules/dotenv/types' not found.
  The file is in the program because:
    Root file specified for compilation

Actually 5 errors in a first line of jsconfig.json:

I don't even use typescript and I didn't set any typescript options while creating Nuxt.js project

jsconfig.json content:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"],
      "~~/*": ["./*"],
      "@@/*": ["./*"]
    }
  },
  "exclude": ["node_modules", ".nuxt", "dist"]
}

I don't understand where they come from.
How do I get rid of this errors?
There's no option quick fix so I can't ignore errors for entire file

Body:
In my case the problem was that the project is in a subfolder inside monorepo.

So the solution was changing it into add ./ before node_modules:

"exclude": ["./node_modules", ".nuxt", "dist"],


问:
What the logic behind b1 ? b1 : b2 in my coding in if-conditions?
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

```<code>function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}
</code>```

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

```<code>actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 2

```<code>actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 3

```<code>actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 4

```<code>actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

答:
b1 ? b1: b2  is using Ternary Operation

In simple words it can be interpreted as

```<code>   condition ? (statement when condition is True) : (statement when condition is false)
</code>```

Since it is using three operands , hence called Ternary(three) Operation.

So, b1 ? b1: b2  means if b1 is true, then return b1 else return b2.

You can also break it to if else statement like this:

```<code>if(b1 === true)
 return b1;
else
 return b2;
</code>```

Body:
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 2

actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 3

actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 4

actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

Body:
b1 ? b1: b2  is using Ternary Operation

In simple words it can be interpreted as

   condition ? (statement when condition is True) : (statement when condition is false)

Since it is using three operands , hence called Ternary(three) Operation.

So, b1 ? b1: b2  means if b1 is true, then return b1 else return b2.

You can also break it to if else statement like this:

if(b1 === true)
 return b1;
else
 return b2;


问:
How to add cookies in chrometemp folder
I opened the Cookies file in my chrome temp folder through sqlite and imported the cookies, but when I open the browser again, the cookies I added are gone.

Is there any way to add cookies?

答:
Add the code below:

```<code>    from selenium.webdriver.chrome.options import Options
    opts = webdriver.ChromeOptions()
    opts.add_argument("user-data-dir='/YOUR CHROME DIR/'")
    driver = webdriver.Chrome(options=opts)
</code>```

remember to replace '/YOUR CHROME DIR/' ,

opts.add_argument("user-data-dir='/YOUR CHROME DIR/'")

this line will store all your session data.

Title: How to add cookies in chrometemp folder

Body:
Add the code below:

    from selenium.webdriver.chrome.options import Options
    opts = webdriver.ChromeOptions()
    opts.add_argument("user-data-dir='/YOUR CHROME DIR/'")
    driver = webdriver.Chrome(options=opts)

remember to replace '/YOUR CHROME DIR/' ,

opts.add_argument("user-data-dir='/YOUR CHROME DIR/'")

this line will store all your session data.


问:
SwiftUI how to center position an item in VStack
I have a simple view like this:

```<code>    let state = viewModel.state

    VStack {

      // "Come back tomorrow!" label
      Text(loc(.comeBackTomorrow))
        .withMainBodyStyle()

      if state.isRewardable && viewModel.isVideoAdReady {

        // "One more joke?" button
        SUIBorderedTextButton(
          title: loc(.oneMoreJokeButtonTitle),
          fontSize: font_size_one_more_joke_button,
          backgroundColor: color_one_more_joke_button,
          enabled: true)
        {
          AdUtil.showVideoAd()
        }
      }
    }
</code>```

This code is the content region in this screenshot, excluding the toolbar on the bottom:

Note that "Come back tomorrow!" label is roughly positioned at 1/3 of the VStack, and "One more joke?" button is roughly at 2/3 of the VStack.

Now I need to position VStack items such that "Come back tomorrow!" label is in the center of the VStack, and "One more joke?" button is slightly below "Come back tomorrow!" label. How can I do that?

Edit:

I tried this code in the answer by @Asperi:

```<code>VStack {
  Spacer()

  Text("Label")    // << your label view here

  Spacer().overlay(Group {
     if condition {
        Button("Title") {}     // << your button here
     }
  }, alignment: .top)

}
</code>```

And got this result:

答:
A possible approach is to use Color.clear and overlay, like

```<code>VStack {
  Color.clear

  Text("Label")    // << your label view here

  Color.clear.overlay(Group {
     if condition {
        Button("Title") {}     // << your button here
     }
  }, alignment: .top)

}
</code>```

Body:
I have a simple view like this:

    let state = viewModel.state

    VStack {

      // "Come back tomorrow!" label
      Text(loc(.comeBackTomorrow))
        .withMainBodyStyle()

      if state.isRewardable && viewModel.isVideoAdReady {

        // "One more joke?" button
        SUIBorderedTextButton(
          title: loc(.oneMoreJokeButtonTitle),
          fontSize: font_size_one_more_joke_button,
          backgroundColor: color_one_more_joke_button,
          enabled: true)
        {
          AdUtil.showVideoAd()
        }
      }
    }

This code is the content region in this screenshot, excluding the toolbar on the bottom:

Note that "Come back tomorrow!" label is roughly positioned at 1/3 of the VStack, and "One more joke?" button is roughly at 2/3 of the VStack.

Now I need to position VStack items such that "Come back tomorrow!" label is in the center of the VStack, and "One more joke?" button is slightly below "Come back tomorrow!" label. How can I do that?

Edit:

I tried this code in the answer by @Asperi:

VStack {
  Spacer()

  Text("Label")    // << your label view here

  Spacer().overlay(Group {
     if condition {
        Button("Title") {}     // << your button here
     }
  }, alignment: .top)

}

And got this result:

Body:
A possible approach is to use Color.clear and overlay, like

VStack {
  Color.clear

  Text("Label")    // << your label view here

  Color.clear.overlay(Group {
     if condition {
        Button("Title") {}     // << your button here
     }
  }, alignment: .top)

}


问:
How to force Chrome's script debugger to reload javascript?
I really like the ability to edit javascript in the chrome debugger however, I find that it can be really problematic getting the debugger to re-fetch the JavaScript from the server.

Sometimes I have to go as far just closing the debugger and reloading the frame works OK - but other times (an dI cannot pin down under what conditions this occurs) I have to clear my temporary internet cache.  Sometimes I swear I have to close chrome completely, then clear the cache and then load the page before the debugger finally shows me the most up-to-date script.

(NB.  There is no caching of the script by the web server)

I was wondering if anyone knew of a quick and easy way to tell the debugger to invalidate all its javascript and fetch it all anew on page reload?

答:
While you are developing your script, try disabling the Chrome cache.

When you reload the page, the JavaScript should now get refreshed.

Chrome circa 2011

Chrome circa 2018

You can also access it on the network tab:


问:
I want to change the location of .sln and .vcxproj
below one is the current project structure.

```<code>- project
  - bin
  - obj
  - include
  - src
    * a.cpp
  * project.sln
  * project.vcxproj
</code>```

But I want to create new directory "project". And move .sln and .vcxproj file into "project" directory.

```<code>- project
  - bin
  - obj
  - include
  - project
    * project.sln
    * project.vcxproj
  - src
    * a.cpp
</code>```

Here problem occurred. Because <ItemGroup> components of vcxproj do not update itself, so .sln cannot load all of my files.

In other words, originally a.cpp is written as "src/a.cpp" in .vcxproj file. but after moving .vcxproj, it still remains as "src/a.cpp" not "../src/a.cpp".

I also saw VS 2010, change location of project file. But I could not find the automatic way to update vcxproj when it is moved.

Is there any way to achieve it ? or I have to change all of components of .vcxproj manually?

答:
Visual Studio just allows to save the solution file .sln at another location. Just select the Solution in the Solution Explorer, go to menu item

File -> Save >MySolution.sln> As...

and save it under another name and/or location.

The project file .vcxproj itself cannot be relocated by a Visual Studio option/menu item. Therefore this has to be done manually and all the pathes to source, resource files etc. shall be updated by the help of a powerful text editor, e.g.

Notepad++

PSPad

TextPad

just doing a search and replace.

Checked with Visual Studio version 16, hence VS 2019. Maybe this option will be available in a future version of Visual Studio.

Body:
below one is the current project structure.

- project
  - bin
  - obj
  - include
  - src
    * a.cpp
  * project.sln
  * project.vcxproj

But I want to create new directory "project". And move .sln and .vcxproj file into "project" directory.

- project
  - bin
  - obj
  - include
  - project
    * project.sln
    * project.vcxproj
  - src
    * a.cpp

Here problem occurred. Because <ItemGroup> components of vcxproj do not update itself, so .sln cannot load all of my files.

In other words, originally a.cpp is written as "src/a.cpp" in .vcxproj file. but after moving .vcxproj, it still remains as "src/a.cpp" not "../src/a.cpp".

I also saw VS 2010, change location of project file. But I could not find the automatic way to update vcxproj when it is moved.

Is there any way to achieve it ? or I have to change all of components of .vcxproj manually?


问:
Any alternate way to execute the program faster

n,k,m=map(int,input().split())
s=input()
while m>0:
    pre=len(s)
    for i in s:
        s+=str(int(i)*k)
    s=s[pre:]
    m-=1
print(len(s))
```
<p>Aim is to determine the number of white balls after M levels. Note that K remains the same for every level.</p>
<p>n,m,k are integers and s is string called power of ball(0<=s>=9) , s is single digit</p>
```INPUT-4 9 2
5418
OUTPUT-14
Exlanation-Initially S=5418
After the 1st, level S=4536972
After the 2nd level, S=36452754816318
length of s is 14
```

答:
```<code>n, k, m = map(int, input().split())
s = input()
for m in range(m, 0, -1):
    pre = len(s)
    for i in s:
        s += str(int(i) * k)
    s = s[pre:]
print(len(s))
</code>```

Code above has O(m*s) time Complexity

Body:
n,k,m=map(int,input().split())
s=input()
while m>0:
    pre=len(s)
    for i in s:
        s+=str(int(i)*k)
    s=s[pre:]
    m-=1
print(len(s))

Aim is to determine the number of white balls after M levels. Note that K remains the same for every level.

n,m,k are integers and s is string called power of ball(0<=s>=9) , s is single digit

INPUT-4 9 2
5418
OUTPUT-14
Exlanation-Initially S=5418
After the 1st, level S=4536972
After the 2nd level, S=36452754816318
length of s is 14

Body:
n, k, m = map(int, input().split())
s = input()
for m in range(m, 0, -1):
    pre = len(s)
    for i in s:
        s += str(int(i) * k)
    s = s[pre:]
print(len(s))

Code above has O(m*s) time Complexity


问:
How to execute Javascript in browser with Python Selenium and record output
I am inquiring about executing javascript in the browser with selenium. I've seen plenty of ways how to do this, however, saving the output to a variable seems to be something else.

```<code>r = driver.execute_script("`; ${document.cookie}`.split(`; bearer_token=`).pop().split(';').shift()")
</code>```

This makes R = None, which is not the output of the code.

答:
You have to add the return statement:

```<code>r = driver.execute_script("return 2+2")
print(r)
</code>```

will print 4.

And it will print None without return.

Body:
I am inquiring about executing javascript in the browser with selenium. I've seen plenty of ways how to do this, however, saving the output to a variable seems to be something else.

r = driver.execute_script("`; ${document.cookie}`.split(`; bearer_token=`).pop().split(';').shift()")

This makes R = None, which is not the output of the code.

Body:
You have to add the return statement:

r = driver.execute_script("return 2+2")
print(r)

will print 4.

And it will print None without return.


问:
Tomcat context is empty when accessed via executor and runnable
Hello I have a web application running on apache-tomee-plus-8.0.1. My problem is about getting an Environment variable from a runnable in a custom executor. The variable is defined in /conf/context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>

<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- disable the scan  in order to avoid errors at startup due to ora18n.jar-->
    <JarScanner scanManifest="false"  scanClassPath="false" scanBootstrapClassPath="false"></JarScanner>

    <!-- base64 from user:pass -->
    <Environment name="myCreds"
    value="toto" type="java.lang.String" />

</Context>
</code>```

The function I use to get the variable "myCreds"

```<code> private static String getCredentialsFromContext() throws NamingException {
        Context initialContext = new InitialContext();
        Context environmentContext = (Context) initialContext.lookup("java:comp/env");
        return (String) environmentContext.lookup("myCreds");
    }
</code>```

This function is called via a JAX-RS endpoint which is used to start long background maintenance tasks of the server application. The progress of the background task is then available on another endpoint.
If I do

```<code>    @GET
    @Path("/testOK")
    public static String testOK() {
          return getCredentialsFromContext(); // works fine
    }
</code>```

But when I use an executor, the lookup fails with
javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp].

```<code>    private static ExecutorService index_executor;
    @GET
    @Path("/testKO")
    public static Response testKO() {
          if (index_executor == null){
               index_executor = Executors.newFixedThreadPool(5);
          }
          index_executor.submit(new Runnable() {

            @Override
            public void run() {
                System.out.println(getCredentialsFromContext()); // FAIL
            }
        });
        return Response.ok.build()
    }
</code>```

It looks like the InitialContext is not the same when called from the runnable. I would like to avoid to pass through args the value of "myCreds". I tried to move the declaration of "myCreds" in the context.xml of the webapp but it didn't help. Using JNDIContext also fails.
Do you understand what is the problem and why the context is different?

Thanks :)

答:
JNDI lookups depend on some context information on the running thread, usually the context class loader.

On a Java EE/Jakarta EE server you should not spawn new (unmanaged) threads yourself, but use the ManagedExecutorService provided by the container. This service automatically propagates some kinds of contexts from the calling thread:

The types of contexts to be propagated from a contextualizing application component include JNDI naming context, classloader, and security information. Containers must support propagation of these context types.

(Jakarta Concurrency Specification, emphasis mine)

You can inject a ManagedExecutorService using a @Resource annotation:

    @Resource
    private ManagedExecutorService executorService;
```
<p><s>Using a <code>ManagedExecutorService</code> works on Wildfly, but on TomEE there is IMHO a bug that prevents the propagation of the naming context: JAX-RS resources use <code>CxfContainerClassLoader</code> as context classloader, which wraps the real classloader, preventing it from propagating to the managed thread.</s></p>
<p><s>A workaround would consist in switching temporarily to the wrapped classloader:</s></p>
<pre class="lang-java prettyprint-override"><code>        final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        if (tccl instanceof org.apache.openejb.util.classloader.Unwrappable) {
            final ClassLoader cl = ((org.apache.openejb.util.classloader.Unwrappable) tccl).unwrap();
            Thread.currentThread().setContextClassLoader(cl);
        }
        executorService.submit(...);
        Thread.currentThread().setContextClassLoader(tccl);
</code>```

Edit: actually, it is enough to mark the JAX-RS resource as @Stateless for the correct propagation of the JNDI naming context.

Body:
Hello I have a web application running on apache-tomee-plus-8.0.1. My problem is about getting an Environment variable from a runnable in a custom executor. The variable is defined in /conf/context.xml:

<?xml version="1.0" encoding="UTF-8"?>

<Context>

    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <JarScanner scanManifest="false"  scanClassPath="false" scanBootstrapClassPath="false"></JarScanner>

    <Environment name="myCreds"
    value="toto" type="java.lang.String" />

</Context>

The function I use to get the variable "myCreds"

 private static String getCredentialsFromContext() throws NamingException {
        Context initialContext = new InitialContext();
        Context environmentContext = (Context) initialContext.lookup("java:comp/env");
        return (String) environmentContext.lookup("myCreds");
    }

This function is called via a JAX-RS endpoint which is used to start long background maintenance tasks of the server application. The progress of the background task is then available on another endpoint.
If I do

    @GET
    @Path("/testOK")
    public static String testOK() {
          return getCredentialsFromContext(); // works fine
    }

But when I use an executor, the lookup fails with
javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp].

    private static ExecutorService index_executor;
    @GET
    @Path("/testKO")
    public static Response testKO() {
          if (index_executor == null){
               index_executor = Executors.newFixedThreadPool(5);
          }
          index_executor.submit(new Runnable() {

            @Override
            public void run() {
                System.out.println(getCredentialsFromContext()); // FAIL
            }
        });
        return Response.ok.build()
    }

It looks like the InitialContext is not the same when called from the runnable. I would like to avoid to pass through args the value of "myCreds". I tried to move the declaration of "myCreds" in the context.xml of the webapp but it didn't help. Using JNDIContext also fails.
Do you understand what is the problem and why the context is different?

Thanks :)

Body:
JNDI lookups depend on some context information on the running thread, usually the context class loader.

On a Java EE/Jakarta EE server you should not spawn new (unmanaged) threads yourself, but use the ManagedExecutorService provided by the container. This service automatically propagates some kinds of contexts from the calling thread:

The types of contexts to be propagated from a contextualizing application component include JNDI naming context, classloader, and security information. Containers must support propagation of these context types.

(Jakarta Concurrency Specification, emphasis mine)

You can inject a ManagedExecutorService using a @Resource annotation:

    @Resource
    private ManagedExecutorService executorService;

<s>Using a ManagedExecutorService works on Wildfly, but on TomEE there is IMHO a bug that prevents the propagation of the naming context: JAX-RS resources use CxfContainerClassLoader as context classloader, which wraps the real classloader, preventing it from propagating to the managed thread.</s>

<s>A workaround would consist in switching temporarily to the wrapped classloader:</s>

        final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        if (tccl instanceof org.apache.openejb.util.classloader.Unwrappable) {
            final ClassLoader cl = ((org.apache.openejb.util.classloader.Unwrappable) tccl).unwrap();
            Thread.currentThread().setContextClassLoader(cl);
        }
        executorService.submit(...);
        Thread.currentThread().setContextClassLoader(tccl);

Edit: actually, it is enough to mark the JAX-RS resource as @Stateless for the correct propagation of the JNDI naming context.


问:
Css background video
Does someone know how to center this video background?

I tried:

```<code>margin: 0 auto;
text-align: center;
</code>```

So far but none of these worked.

This is my code.

Html:

```<code><video autoplay loop poster="polina.jpg" id="vid">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>
</code>```

Css:

```<code>video#vid {
 position: fixed; right: 0; bottom: 0;
 min-width: 100%; min-height: 100%;
 width: auto; height: auto; z-index: -100;
 background: url(polina.jpg) no-repeat;
 background-size: cover;
 margin: 0 auto;
}
</code>```

How do i center this video background so it removes on the left/right side the same amount if you resize the window? Thanks for helping!

Here is my jsfiddle: http://jsfiddle.net/pwxcvxe8/2/

答: place the video inside a  tag

Title: Css background video

Body:
Does someone know how to center this video background?

I tried:

margin: 0 auto;
text-align: center;

So far but none of these worked.

This is my code.

Html:

<video autoplay loop poster="polina.jpg" id="vid">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>

Css:

video#vid {
 position: fixed; right: 0; bottom: 0;
 min-width: 100%; min-height: 100%;
 width: auto; height: auto; z-index: -100;
 background: url(polina.jpg) no-repeat;
 background-size: cover;
 margin: 0 auto;
}

How do i center this video background so it removes on the left/right side the same amount if you resize the window? Thanks for helping!

Here is my jsfiddle: http://jsfiddle.net/pwxcvxe8/2/

Body: place the video inside a <center> tag


问:
How to improve the design of a page with multiple case statements
My page contains: GridView1, GridView2, Button1, Button2, DropDownList1
I bind Gridviews to the table selected in dropdown like this:

```<code>Dim results as DataTable
Select Case ddl1.SelectedValue
    Case 0
        results = dtZero
    Case 1
        results = dtOne
    Case 2
        results = dtTwo
    Case 3
        results = dtThree
End Select
GridView1.DataSource = results
GridView1.DataBind()
</code>```

Then I have two buttons with the following code:

```<code>Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RunZero()
        Case 1
            RunOne()
        Case 2
            RunTwo()
        Case 3
            RunThree()
    End Select
End Sub
</code>```

And

```<code>Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RemoveZero()
        Case 1
            RemoveOne()
        Case 2
            RemoveTwo()
        Case 3
            RemoveThree()
    End Select
End Sub
</code>```

For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?

Update:
RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.

答:
This was a fun one to solve.  Thank you.

Sounds like you should be using actions.

First Create a class that will keep track of all your "operations" represented by your dropdownlist...

EDIT:  Using Actions instead to show that you can use parameters for your functions if you want or not.

```<code>Class OpMode
    Public DropDownKey As String
    Public RunFunction As Action(Of Int32) 'This one will support a parameter'
    Public RemoveFunction As Action
    Public dt As Data.DataTable

    Sub New(DropDownKey As String, RunFunction As Action(Of Int32), RemoveFunction As Action, dt As Data.DataTable)
        Me.DropDownKey = DropDownKey
        Me.RunFunction = RunFunction
        Me.RemoveFunction = RemoveFunction
        Me.dt = dt
    End Sub
End Class
</code>```

You should already have methods for running your procs.

EDIT: In this example I've allowed a parameter for the "Run" procs...

```<code>Private Sub RunOne(MyVariable As Int32)
    Response.Write("RunOne")
End Sub

Private Sub RunTwo(MyVariable As Int32)
    Response.Write("RunTwo")
End Sub

Private Sub RemoveOne()
    Response.Write("RemoveOne")
End Sub

Private Sub RemoveTwo()
    Response.Write("RemoveTwo")
End Sub
</code>```

I assume you have those datatables somewhere...

```<code>Private dtOne As New Data.DataTable
Private dtTwo As New Data.DataTable
</code>```

Create a readonly property to hold all your OpModes you want to use.  It's light to recreate so no need to cache it.

```<code>Private ReadOnly Property OpModes As List(Of OpMode)
    Get
        Dim _OpModes As New List(Of OpMode)

        _OpModes.Add(New OpMode("1", AddressOf RunOne, AddressOf RemoveOne, dtOne))
        _OpModes.Add(New OpMode("2", AddressOf RunTwo, AddressOf RemoveTwo, dtTwo))

        Return _OpModes
    End Get
End Property
</code>```

Make a function for searching through your list of opmodes for the one that matches your dropdownlist...

```<code>Private Function GetOpByDropDownKey(DropDownKey As String) As OpMode
    Return (From x In OpModes Where x.DropDownKey = DropDownKey).First
End Function
</code>```

Make a click event that works for both buttons and invokes the appropriate method...

EDIT:  In this example, the RunFunction has a parameter but the RemoveFunction does not.

```<code>Private Sub btn_Click(sender As Object, e As System.EventArgs) Handles btn1.Click, btn2.Click
    With GetOpByDropDownKey(dd1.SelectedValue)
        If sender Is btn1 Then
            .RunFunction(12345)
        Else
            .RemoveFunction()
        End If
    End With
End Sub
</code>```

Now you can bind the correct datatable programmatically...

```<code>GridView1.DataSource = GetOpByDropDownKey(dd1.SelectedValue).dt
GridView1.DataBind()
</code>```

This should be a lot easier to maintain once you get it working.  You will have less places where you could have accidently forgotten to include an item in your case statement, since all that definition is defined once in your readonly property.

EDIT: (Removed note about delegates.  Actions are all you need.)

I hope this helps you.

Body:
My page contains: GridView1, GridView2, Button1, Button2, DropDownList1
I bind Gridviews to the table selected in dropdown like this:

Dim results as DataTable
Select Case ddl1.SelectedValue
    Case 0
        results = dtZero
    Case 1
        results = dtOne
    Case 2
        results = dtTwo
    Case 3
        results = dtThree
End Select
GridView1.DataSource = results
GridView1.DataBind()

Then I have two buttons with the following code:

Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RunZero()
        Case 1
            RunOne()
        Case 2
            RunTwo()
        Case 3
            RunThree()
    End Select
End Sub

And

Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RemoveZero()
        Case 1
            RemoveOne()
        Case 2
            RemoveTwo()
        Case 3
            RemoveThree()
    End Select
End Sub

For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?

Update:
RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.

Body:
This was a fun one to solve.  Thank you.

Sounds like you should be using actions.

First Create a class that will keep track of all your "operations" represented by your dropdownlist...

EDIT:  Using Actions instead to show that you can use parameters for your functions if you want or not.

Class OpMode
    Public DropDownKey As String
    Public RunFunction As Action(Of Int32) 'This one will support a parameter'
    Public RemoveFunction As Action
    Public dt As Data.DataTable

    Sub New(DropDownKey As String, RunFunction As Action(Of Int32), RemoveFunction As Action, dt As Data.DataTable)
        Me.DropDownKey = DropDownKey
        Me.RunFunction = RunFunction
        Me.RemoveFunction = RemoveFunction
        Me.dt = dt
    End Sub
End Class

You should already have methods for running your procs.

EDIT: In this example I've allowed a parameter for the "Run" procs...

Private Sub RunOne(MyVariable As Int32)
    Response.Write("RunOne")
End Sub

Private Sub RunTwo(MyVariable As Int32)
    Response.Write("RunTwo")
End Sub

Private Sub RemoveOne()
    Response.Write("RemoveOne")
End Sub

Private Sub RemoveTwo()
    Response.Write("RemoveTwo")
End Sub

I assume you have those datatables somewhere...

Private dtOne As New Data.DataTable
Private dtTwo As New Data.DataTable

Create a readonly property to hold all your OpModes you want to use.  It's light to recreate so no need to cache it.

Private ReadOnly Property OpModes As List(Of OpMode)
    Get
        Dim _OpModes As New List(Of OpMode)

        _OpModes.Add(New OpMode("1", AddressOf RunOne, AddressOf RemoveOne, dtOne))
        _OpModes.Add(New OpMode("2", AddressOf RunTwo, AddressOf RemoveTwo, dtTwo))

        Return _OpModes
    End Get
End Property

Make a function for searching through your list of opmodes for the one that matches your dropdownlist...

Private Function GetOpByDropDownKey(DropDownKey As String) As OpMode
    Return (From x In OpModes Where x.DropDownKey = DropDownKey).First
End Function

Make a click event that works for both buttons and invokes the appropriate method...

EDIT:  In this example, the RunFunction has a parameter but the RemoveFunction does not.

Private Sub btn_Click(sender As Object, e As System.EventArgs) Handles btn1.Click, btn2.Click
    With GetOpByDropDownKey(dd1.SelectedValue)
        If sender Is btn1 Then
            .RunFunction(12345)
        Else
            .RemoveFunction()
        End If
    End With
End Sub

Now you can bind the correct datatable programmatically...

GridView1.DataSource = GetOpByDropDownKey(dd1.SelectedValue).dt
GridView1.DataBind()

This should be a lot easier to maintain once you get it working.  You will have less places where you could have accidently forgotten to include an item in your case statement, since all that definition is defined once in your readonly property.

EDIT: (Removed note about delegates.  Actions are all you need.)

I hope this helps you.


问:
What is app-ads.txt and how do I implement it in AdMob?
I received mail from Google AdMob titled AdMob is launching support for app-ads.txt

Can anyone suggest what I have to do in my existing Android Application?

答:
I agree with @Himansu Malik's Answer. I want to add more information here that if you don't have your own domain you can manage it in 2 ways.

Host ads.txt file on firebase.

app-ads-txt website link and follow bellow steps.

Just signup on the website.

then add your google play live app URL.

Copy pub-ID from your add mob account for that you need to press
View All Apps -> Set up app-ads.txt from the top right button.

Add that copied line in app-ads-txt website and in the last one link will

generate add that in your play console account.

a. open app in play console

b. goto options Grow -> Store presence -> store settings

c. paste generated link in the website text field & just press the save button.

5. just goto admob console & View all aps -> apps.ads txt tab section.Expand section detials of app in which you update link & there is one button verfy/update check status blue button just press it once. within few minutes or upto 24 hours it will update.

finally, your app-ads txt file will verify.

Note: Step 5 will be the same for all ways.


问:
How to scrape dates of News Site
I am trying to scrap the news website with news that are valid of a certain date.
The output of the function return :

```<code><li class="meta-data"><time data-datetime="relative" datetime="2022-01-30T08:56:09Z" title="2022-01-30T08:56:09Z">January 30, 2022 08:56</time></li>
</code>```

How can I only print the Date time only?
Printing i.text dont seem to work.

Below is the code.

```<code>import requests
from bs4 import BeautifulSoup
import datetime as datetime
from datetime import timedelta
import pandas as pd
pd.set_option('display.max_columns',None)
pd.set_option('max_colwidth',None)

def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        small_soup2 = soup2.find_all('li', {'class': 'meta-data'})
        #print(small_soup2)
        for i in small_soup2:
            print(i)

okx_scrap()
</code>```

Title: How to scrape dates of News Site

Body:
I am trying to scrap the news website with news that are valid of a certain date.
The output of the function return :

<time data-datetime="relative" datetime="2022-01-30T08:56:09Z" title="2022-01-30T08:56:09Z">January 30, 2022 08:56</time>

How can I only print the Date time only?
Printing i.text dont seem to work.

Below is the code.

import requests
from bs4 import BeautifulSoup
import datetime as datetime
from datetime import timedelta
import pandas as pd
pd.set_option('display.max_columns',None)
pd.set_option('max_colwidth',None)

def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        small_soup2 = soup2.find_all('li', {'class': 'meta-data'})
        #print(small_soup2)
        for i in small_soup2:
            print(i)

okx_scrap()

Body:
you can use regex:

import re

string = '<li class="meta-data"><time data-datetime="relative" datetime="2022-01-30T08:56:09Z" title="2022-01-30T08:56:09Z">January 30, 2022 08:56</time></li>'

datetime= r"(\d{1,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}Z)"

output = re.findall(datetime, string)

#output:

['2022-01-30T08:56:09Z', '2022-01-30T08:56:09Z']


问:
ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
I am facing an issue with my flutter project while trying to establish a google sign in.
I followed the steps in this article:
https://www.freecodecamp.org/news/how-to-integrate-your-ios-flutter-app-with-firebase-on-macos-6ad08e2714f0/

No i am facing this issue:

```<code>Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                            9,1s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **
Xcode's output:
↳
    note: Using new build system
    note: Planning build
    note: Constructing build description
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner')

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.
</code>```

答:
My case: Missing Debug.xcconfig, Release.xcconfig.

My solution: Create a new project => run => Go to folder: ios/Flutter and copy 2 files.

Body:
I am facing an issue with my flutter project while trying to establish a google sign in.
I followed the steps in this article:
https://www.freecodecamp.org/news/how-to-integrate-your-ios-flutter-app-with-firebase-on-macos-6ad08e2714f0/

No i am facing this issue:

Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                            9,1s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **
Xcode's output:
↳
    note: Using new build system
    note: Planning build
    note: Constructing build description
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    error: /Users/zagliz/Desktop/testa/ios/Flutter/Debug.xcconfig:3: could not find included file 'Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' from project 'Runner')
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner')

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.


答:
Don't use find_all but find because there is only one entry in each page and extract time markup and not li:

```<code>def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        print(soup2.find('time')['datetime'])
</code>```

Output:

```<code>>>> okx_scrap()
2022-01-30T08:56:09Z
2022-01-29T05:41:18Z
2022-01-28T10:15:02Z
2022-01-28T07:29:11Z
2022-01-28T06:45:48Z
2022-01-28T03:13:18Z
...
</code>```

Title: How to scrape dates of News Site

Body:
Don't use find_all but find because there is only one entry in each page and extract time markup and not li:

def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        print(soup2.find('time')['datetime'])

Output:

>>> okx_scrap()
2022-01-30T08:56:09Z
2022-01-29T05:41:18Z
2022-01-28T10:15:02Z
2022-01-28T07:29:11Z
2022-01-28T06:45:48Z
2022-01-28T03:13:18Z
...


问:
C program doesn't print output terminal
This is a program to store all possible combinations of given array in the array ans[][].

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

int ingredients = 10;
int ans[10][10];
int x = 0;

void makeCombination(int arr1[], int data[], int st, int end, int index, int r);

void CombinationDisplay(int arr1[], int n, int r) {
    int data[r];
    makeCombination(arr1, data, 0, n - 1, 0, r);
}

void makeCombination(int arr1[], int data[], int st, int end, int index, int r) {
    if (index == r) {
        for (int j = 0; j < r; j++)
            ans[x][j] = data[j];
        x++;
        return;
    }
    for (int i = st; i <= end && end - i + 1 >= r - index; i++) {
        data[index] = arr1[i];
        makeCombination(arr1, data, i + 1, end, index + 1, r);
    }
}

int main() {
    int arr1[ingredients], i;

    for (i = 0; i < ingredients; i++)
        arr1[i] = i;
    int n = sizeof(arr1) / sizeof(arr1[0]);

    for (int r = 0; r < ingredients; r++)
        CombinationDisplay(arr1, n, r);

    for (i = 0; i < ingredients; i++) {
        for (int j = 0; j < i; j++) {
            printf("%d", ans[i][j]);
        }
        printf("\n");
    }
    return 0;
}
</code>```

It should store all the combinations in an array ans and print it. However, it does not show any errors, nor output in the terminal.

答:
There are multiple problems in your code:

int ans[10][10]; is not large enough for all combinations of 10 elements: there are 210 possible combinations (subsets of a set of 10 elements).

printing initial subsets of subsets would produce many duplicates.

a recursive approach is not as simple as an iterative approach for this problem.

Here is a modified version:

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

#define INGREDIENTS 10  // must be in the range 1 to 30 for 32-bit int

int main() {
    for (int i = 0; i < (1 << INGREDIENTS); i++) {
        for (int j = 0; j < INGREDIENTS; j++) {
            if (i & (1 << j))
                printf("%u ", j);
        }
        printf("\n");
    }
    return 0;
}
</code>```

Title: C program doesn't print output terminal

Body:
This is a program to store all possible combinations of given array in the array ans[][].

#include <stdio.h>

int ingredients = 10;
int ans[10][10];
int x = 0;

void makeCombination(int arr1[], int data[], int st, int end, int index, int r);

void CombinationDisplay(int arr1[], int n, int r) {
    int data[r];
    makeCombination(arr1, data, 0, n - 1, 0, r);
}

void makeCombination(int arr1[], int data[], int st, int end, int index, int r) {
    if (index == r) {
        for (int j = 0; j < r; j++)
            ans[x][j] = data[j];
        x++;
        return;
    }
    for (int i = st; i <= end && end - i + 1 >= r - index; i++) {
        data[index] = arr1[i];
        makeCombination(arr1, data, i + 1, end, index + 1, r);
    }
}

int main() {
    int arr1[ingredients], i;

    for (i = 0; i < ingredients; i++)
        arr1[i] = i;
    int n = sizeof(arr1) / sizeof(arr1[0]);

    for (int r = 0; r < ingredients; r++)
        CombinationDisplay(arr1, n, r);

    for (i = 0; i < ingredients; i++) {
        for (int j = 0; j < i; j++) {
            printf("%d", ans[i][j]);
        }
        printf("\n");
    }
    return 0;
}

It should store all the combinations in an array ans and print it. However, it does not show any errors, nor output in the terminal.

Body:
There are multiple problems in your code:

int ans[10][10]; is not large enough for all combinations of 10 elements: there are 210 possible combinations (subsets of a set of 10 elements).

printing initial subsets of subsets would produce many duplicates.

a recursive approach is not as simple as an iterative approach for this problem.

Here is a modified version:

#include <stdio.h>

#define INGREDIENTS 10  // must be in the range 1 to 30 for 32-bit int

int main() {
    for (int i = 0; i < (1 << INGREDIENTS); i++) {
        for (int j = 0; j < INGREDIENTS; j++) {
            if (i & (1 << j))
                printf("%u ", j);
        }
        printf("\n");
    }
    return 0;
}


问:
How to identify entity from a the scenario below?
Here's the given problem:

Client wants to create a movie app

Different movie theatres can register to be on this app

Each theatre can input their different outlets

Each outlet can offer many movies.

Each movie can be cast in multiple outlets

Customer can view multiple movies to showtime

Each movie showtime can be viewed by multiple customers

One outlet will maintain multiple customers

With my limited knowledge, I can list out some of the possible Entities but I'm not confident or 100% sure if it's correct.

Identify the Entities :

Client

Customers

Movie Outlet

Movie Theatres

Movie Screenings

Showtime

I was wondering if Movie App is also an entity but for now I am guessing it is not. Thanks for your help in advance!

答:
You've overseen one major entity: Movies.

The "Movie App" is no entity, just replace with "the backend database".

Screening and showtime are probably the same thing?


问:
How to split dynamic string and then apply pivot operation
I need to perform split operation on a dynamic string like this,

```<code>'John Smith, US, 1001'
</code>```

It seems simple at first but this string might be dynamic in nature, which means sometimes it can have more comma-separated values.

For example:

```<code>'Conrad Smith, UK, 1005, Permanent, 2021'
</code>```

How can I split this dynamic string and perform pivot where I don't have specific number of values to make columns.

答:
Generally you'll need a dynamic sql as number of columns is not known. Case when there exists a limit of the number, say no more then 7 columns you can use a static version

```<code>select * into tbl
from (
  values
    (1,'Conrad Smith, UK, 1005, Permanent, 2021')
) t(id, s);

select *
from tbl
cross apply (
  select [1],[2],[3],[4],[5],[6],[7]
  from (
    select value, row_number() over(order by (select 1))  rn
    from string_split(s, ',')
  ) t
  pivot (max(value) for rn in ([1],[2],[3],[4],[5],[6],[7])) p
) t
</code>```

Note string_split does not guarantee the order of tokens. I guess it is not a problem here, otherwise use a custom splitter.

Body:
I need to perform split operation on a dynamic string like this,

'John Smith, US, 1001'

It seems simple at first but this string might be dynamic in nature, which means sometimes it can have more comma-separated values.

For example:

'Conrad Smith, UK, 1005, Permanent, 2021'

How can I split this dynamic string and perform pivot where I don't have specific number of values to make columns.

Body:
Generally you'll need a dynamic sql as number of columns is not known. Case when there exists a limit of the number, say no more then 7 columns you can use a static version

select * into tbl
from (
  values
    (1,'Conrad Smith, UK, 1005, Permanent, 2021')
) t(id, s);

select *
from tbl
cross apply (
  select [1],[2],[3],[4],[5],[6],[7]
  from (
    select value, row_number() over(order by (select 1))  rn
    from string_split(s, ',')
  ) t
  pivot (max(value) for rn in ([1],[2],[3],[4],[5],[6],[7])) p
) t

Note string_split does not guarantee the order of tokens. I guess it is not a problem here, otherwise use a custom splitter.


问:
Identifying entities for a scenario
Here is the scenario :

"A placement agency which extends its services to organizations and individuals. Candidates register their details like personal, academics, skill set and experience. Organizations give their requirements in terms of skill set, qualification, experience etc. The agency maintains a website through which registration can be done. Site also allows updating candidate profiles and organization requirements. It also gives facility to search job and suitable candidates."

What would be the entities here?

答:
Agency

Candidates

Organizations

Website

My guess is this

Title: Identifying entities for a scenario


问:
I am having this issue in .format() , Can anyone elaborate this to me?
print("My result is {result:2.2f}".format(result)) is not working I had to assign result as r to make the code work.

答:
Just in case, here is the screenshot that the OP linked to:

What is happening in In [7] is that you are giving a keyword result inside the braces {result:2.2f}, so it expects that keyword to be present in the arguments of .format() that you provide later. You have to do it this way:

print("My result is {result:2.2f}".format(result=result))

You have done it correctly in In [8], where the r in the string matches with the keyword argument r=result in the .format() and hence it is able to interpret it correctly.

Btw, you could also simply do - print("My result is {:2.2f}".format(result)).

This way it will see that you haven't specified anything inside the braces and hence look for positional arguments in the .format(), ie: it will look at it in a serial fashion, and hence pick up the first result as the value to be formatted at the first braces {} in the string.

You should have pasted the tries and errors as text in your question to make it more convenient for anyone to answer. I would recommend you to read How to ask for further questions here on :)


问:
Array with only even number
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

```<code>#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done
</code>```

but got errors like:
line 15: syntax error near unexpected token `do'

答:
Try the modulus operator. In almost all languages, it'll look something like this:

```<code>if (x % 2 == 0)    // …Do something
</code>```

That is valid C code, but can easily be applied to other languages.

You can think of the mod operator as a division sign placed in the same location, but rather than returning the results of the division it returns the remainder. Therefore in this code, if the remainder of a divide-by-two is 0, then it divides evenly by two, and so it's even by definition.

Title: Array with only even number

Body:
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done

but got errors like:
line 15: syntax error near unexpected token `do'

Body:
Try the modulus operator. In almost all languages, it'll look something like this:

if (x % 2 == 0)    // …Do something

That is valid C code, but can easily be applied to other languages.

You can think of the mod operator as a division sign placed in the same location, but rather than returning the results of the division it returns the remainder. Therefore in this code, if the remainder of a divide-by-two is 0, then it divides evenly by two, and so it's even by definition.


问:
Can not activate a virtualenv in GIT bash mingw32 for Windows
When I try to activate my virtualenv from GIT bash mingw32 I do not get the expected response.

NOTE: py is the folder for Python projects in my Google Drive folder. hy is the virtualenv folder that was made when I ran virtualenv --distribute hy.

```<code>s3z@s3z ~/Google Drive/py/hy
$ Scripts/activate
</code>```

So you see, there is no expected (hy) that appears before s3z@s3z ~/Google Drive/py/hy

```<code>s3z@s3z ~/Google Drive/py/hy
$ Scripts/activate.bat
Scripts/activate.bat: line 1: @echo: command not found
Scripts/activate.bat: line 4: syntax error near unexpected token `('
Scripts/activate.bat: line 4: `if not defined PROMPT ('
</code>```

And when targeting the actual file name activate.bat I get error messages. Then I try deactivating to see what happens cause I thought maybe virtualenv was activated but hidden.

```<code>s3z@s3z ~/Google Drive/py/hy
$ Scripts/deactivate.bat
Scripts/deactivate.bat: line 1: @echo: command not found
Scripts/deactivate.bat: line 3: syntax error near unexpected token `('
Scripts/deactivate.bat: line 3: `if defined _OLD_VIRTUAL_PROMPT ('

s3z@s3z ~/Google Drive/py/hy
$ Scripts/deactivate
sh.exe": Scripts/deactivate: No such file or directory
</code>```

Any ideas?

答:
I recently had this problem and i found the solution for this.
after you have done

```<code>$ cd Scripts
</code>```

after this you should just simply type

```<code>$ source activate
</code>```

and this will activate your venv

to deactivate just type

```<code>$ deactivate
</code>```

and you venv is deactivated

Body:
When I try to activate my virtualenv from GIT bash mingw32 I do not get the expected response.

NOTE: py is the folder for Python projects in my Google Drive folder. hy is the virtualenv folder that was made when I ran virtualenv --distribute hy.

s3z@s3z ~/Google Drive/py/hy
$ Scripts/activate

So you see, there is no expected (hy) that appears before s3z@s3z ~/Google Drive/py/hy

s3z@s3z ~/Google Drive/py/hy
$ Scripts/activate.bat
Scripts/activate.bat: line 1: @echo: command not found
Scripts/activate.bat: line 4: syntax error near unexpected token `('
Scripts/activate.bat: line 4: `if not defined PROMPT ('

And when targeting the actual file name activate.bat I get error messages. Then I try deactivating to see what happens cause I thought maybe virtualenv was activated but hidden.

s3z@s3z ~/Google Drive/py/hy
$ Scripts/deactivate.bat
Scripts/deactivate.bat: line 1: @echo: command not found
Scripts/deactivate.bat: line 3: syntax error near unexpected token `('
Scripts/deactivate.bat: line 3: `if defined _OLD_VIRTUAL_PROMPT ('

s3z@s3z ~/Google Drive/py/hy
$ Scripts/deactivate
sh.exe": Scripts/deactivate: No such file or directory

Any ideas?

Body:
I recently had this problem and i found the solution for this.
after you have done

$ cd Scripts

after this you should just simply type

$ source activate

and this will activate your venv

to deactivate just type

$ deactivate

and you venv is deactivated