问:
Include file.php + id. Is this possible with php?
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

```<code><a href="news.php?id=<?=$row['id']?>">Read More</a></p>
</code>```

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!

答: Change it to main.php, get the id value on main.php, pass it to your news function.

Body:
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

<a href="news.php?id=<?=$row['id']?>">Read More

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!


来源: stackexchange

问:
Is there a way to get a specific key-value pair from the map?
I am currently learning about maps in STL. I want to know how to get a specific key value pair from the map. For example, 3rd key-value pair from the map below. 'C'-> 1

```<code>    'A'-> 1
    'B'-> 1
    'C'-> 1
    'D'-> 1
    'E'-> 2

</code>```

答:
Yes, we can access "The third key-value pair" of a map, but it's not very straightforward. We need to get an iterator the beginning of the map and then advance it twice (note, that in more generic code you should check that the map has the appropriate size before doing something like this)

```<code>std::map<char, int> my_map;
my_map['C'] = 3;
my_map['A'] = 1;
my_map['B'] = 2;

auto begin = my_map.begin();
std::advance(begin, 2);
std::cout << begin->first << " : " << begin->second << std::endl;
</code>```

Output:

C : 3

Live Demo

Note that the 3rd element is actually the first key-value pair we inserted. This is because keys are inserted in sorted order.

ContentLicense: CC BY-SA 4.0

Body:
I am currently learning about maps in STL. I want to know how to get a specific key value pair from the map. For example, 3rd key-value pair from the map below. 'C'-> 1

    'A'-> 1
    'B'-> 1
    'C'-> 1
    'D'-> 1
    'E'-> 2

Body:
Yes, we can access "The third key-value pair" of a map, but it's not very straightforward. We need to get an iterator the beginning of the map and then advance it twice (note, that in more generic code you should check that the map has the appropriate size before doing something like this)

std::map<char, int> my_map;
my_map['C'] = 3;
my_map['A'] = 1;
my_map['B'] = 2;

auto begin = my_map.begin();
std::advance(begin, 2);
std::cout << begin->first << " : " << begin->second << std::endl;

Output:

C : 3

Live Demo

Note that the 3rd element is actually the first key-value pair we inserted. This is because keys are inserted in sorted order.


问:
Which TAG to use to cancel the job
PeriodicWorkRequest.Builder has addTag method, enqueueUniquePeriodicWork(TAG, policy, periodicWorkRequest) also has the TAG.

Question is which TAG to use in order to cancel all MyWorker task ? Will it be MyWorkerTag or MySchedulerClassTag

```<code>PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
                MyWorker.class,
                PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
                TimeUnit.MILLISECONDS);
        builder.addTag("MyWorkerTag");
        WorkManager.getInstance().enqueueUniquePeriodicWork("MySchedulerClassTag", ExistingPeriodicWorkPolicy.KEEP, builder.build());
</code>```

答:
Both PeriodicWorkRequest.Builder and OneTimeWorkRequest.Builder include a addTag() method that allows you to set a TAG that you can later use to identify a set of work request to observe or cancel them.

In the case of the enqueueUniquePeriodicWork(UniqueName, policy, workrequest), the first parameters is a unique name used by WorkManager to identify each unique work and it is not related to the TAG assigned to the WorkRequest.

So, to cancel your worker you should use the TAG set on the WorkRequest using the setTag method:

```<code>PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
            MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS)
    .addTag("MyWorkerTag")
    .build();

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
            "UniqueName",
            ExistingPeriodicWorkPolicy.KEEP,
            builder);

// Later on, when needed
WorkManager.getInstance(context).cancelAllWorkByTag("MyWorkerTag");
</code>```

More information are available on the documentation:

Cancelling and stopping work

Hadling Unique Work

Title: Which TAG to use to cancel the job

Body:
PeriodicWorkRequest.Builder has addTag method, enqueueUniquePeriodicWork(TAG, policy, periodicWorkRequest) also has the TAG.

Question is which TAG to use in order to cancel all MyWorker task ? Will it be MyWorkerTag or MySchedulerClassTag

PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
                MyWorker.class,
                PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
                TimeUnit.MILLISECONDS);
        builder.addTag("MyWorkerTag");
        WorkManager.getInstance().enqueueUniquePeriodicWork("MySchedulerClassTag", ExistingPeriodicWorkPolicy.KEEP, builder.build());

Body:
Both PeriodicWorkRequest.Builder and OneTimeWorkRequest.Builder include a addTag() method that allows you to set a TAG that you can later use to identify a set of work request to observe or cancel them.

In the case of the enqueueUniquePeriodicWork(UniqueName, policy, workrequest), the first parameters is a unique name used by WorkManager to identify each unique work and it is not related to the TAG assigned to the WorkRequest.

So, to cancel your worker you should use the TAG set on the WorkRequest using the setTag method:

PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
            MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS)
    .addTag("MyWorkerTag")
    .build();

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
            "UniqueName",
            ExistingPeriodicWorkPolicy.KEEP,
            builder);

// Later on, when needed
WorkManager.getInstance(context).cancelAllWorkByTag("MyWorkerTag");

More information are available on the documentation:

Cancelling and stopping work

Hadling Unique Work


问:
How to disable the calendar when it falls on a specific day in a week
I am working on a datepicker that will disable all the selection when the day falls on Friday & Saturday.

I've already created a datepicker that will only select next week's date (with the help of the other member here).

```<code>var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());

$(".datepicker").datepicker({
  minDate: dateMax,
  maxDate: daysTillWeekOver + 6
});
</code>```

I want all the dates on my datepicker will be disabled once the day in the current week falls every Friday and Saturday.

答:
Here's a modified solution based on Lelio's comment.

```<code>$(function() {
  var now = new Date();
  var currentDayOfTheWeek = now.getUTCDay()
  $("#datepicker").datepicker({
    beforeShowDay: function(date) {
      return [currentDayOfTheWeek != 5 && currentDayOfTheWeek != 6, ""];
    }
  });
});
</code>```

Basically, if the current day of the week is Friday or Saturday, the days on the calendar will be disabled.

Body:
I am working on a datepicker that will disable all the selection when the day falls on Friday & Saturday.

I've already created a datepicker that will only select next week's date (with the help of the other member here).

var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());

$(".datepicker").datepicker({
  minDate: dateMax,
  maxDate: daysTillWeekOver + 6
});

I want all the dates on my datepicker will be disabled once the day in the current week falls every Friday and Saturday.

Body:
Here's a modified solution based on Lelio's comment.

$(function() {
  var now = new Date();
  var currentDayOfTheWeek = now.getUTCDay()
  $("#datepicker").datepicker({
    beforeShowDay: function(date) {
      return [currentDayOfTheWeek != 5 && currentDayOfTheWeek != 6, ""];
    }
  });
});

Basically, if the current day of the week is Friday or Saturday, the days on the calendar will be disabled.


答:
If I have understood you correctly you need something like

```<code>#include <iostream>
#include <map>
#include <iterator>

int main()
{
    std::map<char, unsigned int> m =
    {
        { 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
    };

    auto it = std::next( std::begin( m ), std::min<decltype( m )::size_type>( m.size(), 2 ) );

    if ( it != std::end( m ) )
    {
        std::cout << it->first << ": " << it->second << '\n';
    }

    return 0;
}
</code>```

The program output is

```<code>C: 1
</code>```

That is you can use operations with iterators.

Or maybe you need to use just the method find of the class as for example

```<code>#include <iostream>
#include <map>
#include <iterator>

int main()
{
    std::map<char, unsigned int> m =
    {
        { 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
    };

    auto it = m.find( 'C' );

    if ( it != std::end( m ) )
    {
        std::cout << it->first << ": " << it->second << '\n';
    }

    return 0;
}
</code>```

Again the program output is

```<code>C: 1
</code>```

Title: Is there a way to get a specific key-value pair from the map?

Body:
If I have understood you correctly you need something like

#include <iostream>
#include <map>
#include <iterator>

int main()
{
    std::map<char, unsigned int> m =
    {
        { 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
    };

    auto it = std::next( std::begin( m ), std::min<decltype( m )::size_type>( m.size(), 2 ) );

    if ( it != std::end( m ) )
    {
        std::cout << it->first << ": " << it->second << '\n';
    }

    return 0;
}

The program output is

C: 1

That is you can use operations with iterators.

Or maybe you need to use just the method find of the class as for example

#include <iostream>
#include <map>
#include <iterator>

int main()
{
    std::map<char, unsigned int> m =
    {
        { 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
    };

    auto it = m.find( 'C' );

    if ( it != std::end( m ) )
    {
        std::cout << it->first << ": " << it->second << '\n';
    }

    return 0;
}

Again the program output is

C: 1


问:
How to mask email address in Objective-C
How do I mask the email address string in Objective-C?

I want to mask email as follows

mugunth@gmail.com into m*****h@gmail.com

答:
Find the range of @ and create a new range by decreasing 2 from the range location. Create a new string with * characters repeating by the new range length. Now replace the characters from the range.

```<code>NSArray *emails = @[@"mugunth@gmail.com",@"mugunthgmail.com",@"m@gmail.com"];
NSString *emailRegex = @"[A-Z0-9a-z._%+-]{2,}+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
for (NSString *email in emails) {
    if ([emailTest evaluateWithObject:email]) {
        NSRange range = [email rangeOfString:@"@"];
        NSRange newRange = NSMakeRange(1, range.location-2);
        NSString *replace = [@"" stringByPaddingToLength:newRange.length withString:@"*" startingAtIndex:0];
        NSString * maskedEmail = [email stringByReplacingCharactersInRange:newRange withString:replace];
        NSLog(@"%@",maskedEmail);//m*****h@gmail.com
    } else {
        NSLog(@"Invalid Email Address");
    }
}
</code>```

m*****h@gmail.com

Invalid Email Address

Invalid Email Address

Body:
Find the range of @ and create a new range by decreasing 2 from the range location. Create a new string with * characters repeating by the new range length. Now replace the characters from the range.

NSArray *emails = @[@"mugunth@gmail.com",@"mugunthgmail.com",@"m@gmail.com"];
NSString *emailRegex = @"[A-Z0-9a-z._%+-]{2,}+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
for (NSString *email in emails) {
    if ([emailTest evaluateWithObject:email]) {
        NSRange range = [email rangeOfString:@"@"];
        NSRange newRange = NSMakeRange(1, range.location-2);
        NSString *replace = [@"" stringByPaddingToLength:newRange.length withString:@"*" startingAtIndex:0];
        NSString * maskedEmail = [email stringByReplacingCharactersInRange:newRange withString:replace];
        NSLog(@"%@",maskedEmail);//m*****h@gmail.com
    } else {
        NSLog(@"Invalid Email Address");
    }
}

m*****h@gmail.com

Invalid Email Address

Invalid Email Address


问:
Is this possible: Cloning virtual environments to each users laptops while source code and related files remain in a network drive
I've written a model.py script which takes in a csv file, runs a bunch of calculations, then outputs the data into my Dashboard.xlsm file. All of these files are in the same folder in a shared network drive. This .py script needs to be able to be run by clicking a button within the xlsm file. To set this up, I've written a simple VBA macro (linked to the aforementioned button) which runs a .bat file. This .bat file contains shell commands to create a virtual environment in the same folder as my files, and then run my .py script within this venv.

However, activating this venv takes a long time (~ 1 min). If instead I setup a venv in a local folder, I believe it would speed up the runtime considerably.

Top level question: Is my current setup the best way for each user to be able to run my model.py file from within excel, if not, what alternatives are possible?

Mid level question: Is cloning a venv, one on each users laptop, the way to go to speed up my code's runtime, if not, what else could I try to do?

Code specific question: What is the best way to create cloned venv, and ensure each user will run my model.py file from within their own local venv?

My answer to the top level question:

I've spent the better part of the past 2 weeks looking into alternatives. I've tried transforming my .py file into an .exe, but neither myself, nor a colleague of mine were able to get the executable file to run properly (we tried using Pyinstaller and Py2exe).

I then looked into virtual environments, and, through lots of trial and error, finally got a working prototype (but just working for me for now).

My answer to the mid level question:

I honestly don't know and am unsure what to even google to find the answer to this.

My answer to the specific question:

I thought I could do the following to (hopefully) speed up the process:

Instead of saving the venv in the network folder, I would save/create n versions of the venv, one on each user's laptop (in a folder they wouldn't modify).

I create n .bat files, one for each user's specific path information. This is the file which, when run, creates the venv and runs the python script.

In my simple VBA macro, I check which user is using the xlsm file, and activate the correct .bat file accordingly.

Here is what I've coded so far:

The VBA script which calls the bat file

Sub run_model()

    Dim folderPath As String
    Dim shellCommand As String

    ActiveSheet.EnableCalculation = False
    ActiveSheet.EnableCalculation = True

    ActiveWorkbook.save

    folderPath = Application.ActiveWorkbook.Path
    shellCommand = folderPath & "\" & "USER_NAME_GOES_HERE.bat"
    Call Shell(shellCommand, vbNormalFocus)

End Sub
```

<h1>the bat file which sets up the venv and runs the py script</h1>

```chdir I:\NETWORK_PATH
I:

python -m venv venv/
"./venv/Scripts/activate.bat" & pip install -r ./src/requirements.txt & "./venv/Scripts/activate.bat" & python "./src/MODEL.py"
'''
```

<h1>the python script</h1>

```import USER_DEFINED_MODULE #this .py file contains functions I use later on in my script
import other_stuff
```

do stuff then output to dashboard.xlsm

Some final details:

no one has admin rights,

everyone has python installed via anaconda,

I tried installing python independently, but I was unable to make it functional (thus the fallback to the Anaconda distribution),

Yes, I have to use Excel as both the input/output files.

答:
Top level comments:

I'd say using C or C++ with gcc to compile a DLL which the excel vba could interface would be much cleaner.

If you need to/want to use python then you have the problem of writing to an xlsm file while it is open. So the python script has to be kicked off from a different workbook from the one holding the results. But then a shortcut to the script would be just as good.

Best option IMO is to have your model.py always running, monitoring the dir and automatically updating the xlsm when new files are added, or files modified. This probably requires a new book made whenever the csv files are added. You could add the date/time to the file names. This also means no one needs their local machine setup to run your script.

Mid level comments:

Activating your venv shouldn't be slow. It'll just be show the first time to setup the venv. So I'd take the hit unless leave the venv to be setup per user as this is the most robust method.

If most people will only use your script once or be put off after one use due to the slow initialisation routine, then you need something better. The alternative is to get an installer to be run on everyone's computer on next login if your IT department agrees. Or email people with a link which will kick off a background process to set things up for the first time.

Low level comments:

A key would be to not run pip install everytime you run the script. That is slow. Either your venv is setup or not. Just check if the venv dir exists prior to running pip install.

Body:
I've written a model.py script which takes in a csv file, runs a bunch of calculations, then outputs the data into my Dashboard.xlsm file. All of these files are in the same folder in a shared network drive. This .py script needs to be able to be run by clicking a button within the xlsm file. To set this up, I've written a simple VBA macro (linked to the aforementioned button) which runs a .bat file. This .bat file contains shell commands to create a virtual environment in the same folder as my files, and then run my .py script within this venv.

However, activating this venv takes a long time (~ 1 min). If instead I setup a venv in a local folder, I believe it would speed up the runtime considerably.

Top level question: Is my current setup the best way for each user to be able to run my model.py file from within excel, if not, what alternatives are possible?

Mid level question: Is cloning a venv, one on each users laptop, the way to go to speed up my code's runtime, if not, what else could I try to do?

Code specific question: What is the best way to create cloned venv, and ensure each user will run my model.py file from within their own local venv?

My answer to the top level question:

I've spent the better part of the past 2 weeks looking into alternatives. I've tried transforming my .py file into an .exe, but neither myself, nor a colleague of mine were able to get the executable file to run properly (we tried using Pyinstaller and Py2exe).

I then looked into virtual environments, and, through lots of trial and error, finally got a working prototype (but just working for me for now).

My answer to the mid level question:

I honestly don't know and am unsure what to even google to find the answer to this.

My answer to the specific question:

I thought I could do the following to (hopefully) speed up the process:

Instead of saving the venv in the network folder, I would save/create n versions of the venv, one on each user's laptop (in a folder they wouldn't modify).

I create n .bat files, one for each user's specific path information. This is the file which, when run, creates the venv and runs the python script.

In my simple VBA macro, I check which user is using the xlsm file, and activate the correct .bat file accordingly.

Here is what I've coded so far:

The VBA script which calls the bat file

Sub run_model()

    Dim folderPath As String
    Dim shellCommand As String

    ActiveSheet.EnableCalculation = False
    ActiveSheet.EnableCalculation = True

    ActiveWorkbook.save

    folderPath = Application.ActiveWorkbook.Path
    shellCommand = folderPath & "\" & "USER_NAME_GOES_HERE.bat"
    Call Shell(shellCommand, vbNormalFocus)

End Sub

the bat file which sets up the venv and runs the py script

chdir I:\NETWORK_PATH
I:

python -m venv venv/
"./venv/Scripts/activate.bat" & pip install -r ./src/requirements.txt & "./venv/Scripts/activate.bat" & python "./src/MODEL.py"
'''

the python script

import USER_DEFINED_MODULE #this .py file contains functions I use later on in my script
import other_stuff

do stuff then output to dashboard.xlsm

Some final details:

no one has admin rights,

everyone has python installed via anaconda,

I tried installing python independently, but I was unable to make it functional (thus the fallback to the Anaconda distribution),

Yes, I have to use Excel as both the input/output files.


问:
Reverse proxying to static website not working
I have a nginx server running at www.example.com.

Within it, I have set up a reverse proxy to a static website of mine hosted with Zeit now.

```<code>location /apps/app1/ {
    proxy_pass https://app1.username.now.sh;
}
</code>```

However, when I visit www.example.com/apps/app1, I get the correct browser tab name ('React App' in my case as my static website is made with React and the default name is 'React App').

In the browser console, I see the following errors:

```<code>GET https://www.example.com/static/css/1.621e483e.chunk.css net::ERR_ABORTED 404 (Not Found)
GET https://www.example.com/manifest.json 404 (Not Found)
Manifest: Line: 1, column: 1, Unexpected token.
</code>```

I had a similar issue when my static website was hosted at Netlify. The Netlify customer service told me that they don't support reverse proxying, but that I could use their own redirects.

Why am I not able to reverse proxy to a static website at an external URL? Is there a way to fix this?

Update 1:
I'm currently trying to reverse proxy bluprince13.com/apps/renting-vs-buying/ to renting-vs-buying.bluprince13.now.sh

答:
Here's what worked for me, but I only figured it out with the help of the other guys who answered below. In hindsight, it seems so simple and I feel silly for having not figured it out myself!

The response's HTML contains absolute URLs for CSS and JS files. The browser initially loads the HTML page from the /apps/app1 prefix, but then it tries to load assets from /static, /favicon, /css etc. But, there's nothing there!

The problem is that the app uses absolute referencing. All I needed to do was change my app to use relative referencing instead. With React, you can do this easily by putting this in your package.json (see docs here):

```<code>"homepage": ".",
</code>```

Now, the browser will correctly load assets from /apps/app1/static, /apps/app1/favicon, /apps/app1/css etc.

Body:
I have a nginx server running at www.example.com.

Within it, I have set up a reverse proxy to a static website of mine hosted with Zeit now.

location /apps/app1/ {
    proxy_pass https://app1.username.now.sh;
}

However, when I visit www.example.com/apps/app1, I get the correct browser tab name ('React App' in my case as my static website is made with React and the default name is 'React App').

In the browser console, I see the following errors:

GET https://www.example.com/static/css/1.621e483e.chunk.css net::ERR_ABORTED 404 (Not Found)
GET https://www.example.com/manifest.json 404 (Not Found)
Manifest: Line: 1, column: 1, Unexpected token.

I had a similar issue when my static website was hosted at Netlify. The Netlify customer service told me that they don't support reverse proxying, but that I could use their own redirects.

Why am I not able to reverse proxy to a static website at an external URL? Is there a way to fix this?

Update 1:
I'm currently trying to reverse proxy bluprince13.com/apps/renting-vs-buying/ to renting-vs-buying.bluprince13.now.sh

Body:
Here's what worked for me, but I only figured it out with the help of the other guys who answered below. In hindsight, it seems so simple and I feel silly for having not figured it out myself!

The response's HTML contains absolute URLs for CSS and JS files. The browser initially loads the HTML page from the /apps/app1 prefix, but then it tries to load assets from /static, /favicon, /css etc. But, there's nothing there!

The problem is that the app uses absolute referencing. All I needed to do was change my app to use relative referencing instead. With React, you can do this easily by putting this in your package.json (see docs here):

"homepage": ".",

Now, the browser will correctly load assets from /apps/app1/static, /apps/app1/favicon, /apps/app1/css etc.


问:
AWS execute-api endpoint request timeout / dial tcp i/o timeout
I want to access a public Rest Api gateway from a AWS Lambda within a VPC.

I already created an execute-api endpoint and added the 443 port to the security group. I also disabled private DNS Names, but I am still getting a "Endpoint request timed out"/ dial tcp 52.28..:443: i/o timeout error.
I also tested the API I want to access with postman, which works as intended.
What am I missing.

答: try accessing the API using <vpce-id>.execute-api.<region>.vpce.amazonaws.com and passing <api_id>.execute-api.<region>.amazonaws.com in the Host header


问:
Javascript redirection to other page not working
I am working on a WordPress site where am using contact form 7 plugin. Now I want to redirect the page to thank you page and append form id with URL. But every time it redirects to the home page. am using wpcf7mailsent DOM event.

I have searched around for several hours. I have used the following redirection methods

```<code>window.location("/thankyou?submission="+formID);
document.location = 'https://example.com/thankyou'+formID;
document.location.href = '/thankyou?submission='+formID;
window.location.assign('https://example.com/thankyou'+formID);
window.location.replace('https://example.com/thankyou'+formID);
window.location.replace('https://example.com/thankyou'+formID);
jQuery(location).attr('href','example.com/thankyou'+formID);
</code>```

Here is my code

```<code>var nr_wpcf7Elm = document.querySelector( '.wpcf7' );

nr_wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) {
    var inputs = event.detail.inputs;
    var formID = event.detail.contactFormId;
    window.location.href = '/thankyou?submission='+formID;
}, false );
</code>```

I need to redirect the user to a thank you page and I want URL with form ID.

答:
Try using the wpcf7submit event.

```<code>var nr_wpcf7Elm = document.querySelector( '.wpcf7' );

nr_wpcf7Elm.addEventListener( 'wpcf7mailsubmit', function( event ) {
    var inputs = event.detail.inputs;
    var formID = event.detail.contactFormId;
    window.location.href = '/thankyou?submission='+formID;
}, false );
</code>```

Body:
I am working on a WordPress site where am using contact form 7 plugin. Now I want to redirect the page to thank you page and append form id with URL. But every time it redirects to the home page. am using wpcf7mailsent DOM event.

I have searched around for several hours. I have used the following redirection methods

window.location("/thankyou?submission="+formID);
document.location = 'https://example.com/thankyou'+formID;
document.location.href = '/thankyou?submission='+formID;
window.location.assign('https://example.com/thankyou'+formID);
window.location.replace('https://example.com/thankyou'+formID);
window.location.replace('https://example.com/thankyou'+formID);
jQuery(location).attr('href','example.com/thankyou'+formID);

Here is my code

var nr_wpcf7Elm = document.querySelector( '.wpcf7' );

nr_wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) {
    var inputs = event.detail.inputs;
    var formID = event.detail.contactFormId;
    window.location.href = '/thankyou?submission='+formID;
}, false );

I need to redirect the user to a thank you page and I want URL with form ID.

Body:
Try using the wpcf7submit event.

var nr_wpcf7Elm = document.querySelector( '.wpcf7' );

nr_wpcf7Elm.addEventListener( 'wpcf7mailsubmit', function( event ) {
    var inputs = event.detail.inputs;
    var formID = event.detail.contactFormId;
    window.location.href = '/thankyou?submission='+formID;
}, false );


问:
Why does Xcode install all of the Swift libraries (multiple times) to my device when using Podfile?
I just added a Podfile to my iOS project, and no matter what I set for ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES (even $(inherited)), it still adds all of these swift libraries to my builds. My app was around 20 MB before I added the Podfile and now it's 1.35 GB... I have done a fair amount of Googling and I can't seem to figure out what is causing this. I'm using Xcode 10.1 and here's my Podfile:</p>

```<code>platform :ios, '10.0'

target 'MyApp' do
  use_frameworks!

  # Core Dependencies
  pod 'SwiftLint', '~> 0.29.1'
  pod 'R.swift', '~> 5.0.0.rc.1'
  pod 'RxSwift', '~> 4.4.0'
  pod 'RxCocoa',    '~> 4.4.0'
  pod 'Alamofire', '~> 4.8.0'
  pod 'Moya/RxSwift', '~> 12.0.1'

  # Database management
  pod 'RxRealm', :git => 'https://github.com/RxSwiftCommunity/RxRealm', :tag => '0.7.7'
  pod 'RealmSwift', '~> 3.12.0'

  # Remote Image management
  # pod 'Kingfisher', '~> 4.6.3'

  target 'MyAppTests' do
    inherit! :search_paths
    pod 'Nimble', '~> 7.3.1'
    pod 'SnapshotTesting', '~> 1.0'
  end

  target 'MyAppUITests' do
    inherit! :search_paths
    pod 'Nimble', '~> 7.3.1'
    pod 'SnapshotTesting', '~> 1.0'
  end

end
post_install do |installer_representation|
  installer_representation.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = 'YES'
    end
  end
end
</code>```

答:
Well, after many hours of frustration, I finally discovered what was causing the problem. It turns out that I was missing an important step: Clean Build Folder.

Whenever you make a change to the Podfile, you need to rerun pod install and then click 'Clean Build Folder' under the 'Project' menu.

Here is the correct code for the bottom of the Podfile that stops multiple copies of the Swift Standard Libraries from being installed:

```<code>post_install do |installer_representation|
  installer_representation.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = '$(inherited)'
    end
  end
end
</code>```

Once I had done this, my app was back to its original, small size. Happy coding!

Body:
I just added a Podfile to my iOS project, and no matter what I set for ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES (even $(inherited)), it still adds all of these swift libraries to my builds. My app was around 20 MB before I added the Podfile and now it's 1.35 GB... I have done a fair amount of Googling and I can't seem to figure out what is causing this. I'm using Xcode 10.1 and here's my Podfile:

platform :ios, '10.0'

target 'MyApp' do
  use_frameworks!

  # Core Dependencies
  pod 'SwiftLint', '~> 0.29.1'
  pod 'R.swift', '~> 5.0.0.rc.1'
  pod 'RxSwift', '~> 4.4.0'
  pod 'RxCocoa',    '~> 4.4.0'
  pod 'Alamofire', '~> 4.8.0'
  pod 'Moya/RxSwift', '~> 12.0.1'

  # Database management
  pod 'RxRealm', :git => 'https://github.com/RxSwiftCommunity/RxRealm', :tag => '0.7.7'
  pod 'RealmSwift', '~> 3.12.0'

  # Remote Image management
  # pod 'Kingfisher', '~> 4.6.3'

  target 'MyAppTests' do
    inherit! :search_paths
    pod 'Nimble', '~> 7.3.1'
    pod 'SnapshotTesting', '~> 1.0'
  end

  target 'MyAppUITests' do
    inherit! :search_paths
    pod 'Nimble', '~> 7.3.1'
    pod 'SnapshotTesting', '~> 1.0'
  end

end
post_install do |installer_representation|
  installer_representation.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = 'YES'
    end
  end
end

Body:
Well, after many hours of frustration, I finally discovered what was causing the problem. It turns out that I was missing an important step: Clean Build Folder.

Whenever you make a change to the Podfile, you need to rerun pod install and then click 'Clean Build Folder' under the 'Project' menu.

Here is the correct code for the bottom of the Podfile that stops multiple copies of the Swift Standard Libraries from being installed:

post_install do |installer_representation|
  installer_representation.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = '$(inherited)'
    end
  end
end

Once I had done this, my app was back to its original, small size. Happy coding!


问:
Check the content of *args in a Class __init__
I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

```<code>class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()
</code>```

答:
type(my_class.args) is tuple so you can not compare it to a single value, i.e.

if self.args == 'ti':
```

<p>However, you can do </p>

<pre class="lang-py prettyprint-override"><code>if "ti" in self.args and len(self.args) == 1:
</code>```

to check that "ti" is the only input.

Body:
I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()

Body:
type(my_class.args) is tuple so you can not compare it to a single value, i.e.

if self.args == 'ti':

However, you can do

if "ti" in self.args and len(self.args) == 1:

to check that "ti" is the only input.


问:
Getting MonthAndYear name in sql?
I need a small script to get the current month name and current year. So as to create a unique batch to store statements. My preferred format is January2011 or Feb2011 whichever is easier to get. i.e. MonthYear</p>

答: Have a look at the DATEPART function and combine that with finding the name of a month, this SO question/answer has information on doing that.</p>

ContentLicense: CC BY-SA 3.0

Title: Getting MonthAndYear name in sql?


问:
Getting Exception 'java.lang.IllegalStateException:Expected one datasource and found 2' when more than one datasource defined
When i define more than one datasource in my spring cloud task application , it throws an exception. This is how i have defined the datasources

```<code>@Primary
@Bean(name="datasource1")
@ConfigurationProperties(prefix="spring.datasource")
public javax.sql.DataSource primaryDataSource() {
    return  DataSourceBuilder.create().build();
}

@Bean(name="datasource2")
@ConfigurationProperties(prefix="spring.datasource1")
public javax.sql.DataSource primaryDataSource1() {
    return  DataSourceBuilder.create().build();
}

@Bean
public TaskConfigurer taskConfigurer() {
    return new DefaultTaskConfigurer(primaryDataSource());
}
</code>```

I have seen suggestions to put @Primary , defining TaskConfigurer like above, but none of them is working.Has any one faced this kind of problem ?

Thanks,
Neel

答:
You need to override DefaultTaskConfigurer</p>

```<code>@Configuration
public class BatchConfigurer extends DefaultTaskConfigurer
{

    public BatchConfigurer(@Qualifier("batchDataSource") DataSource dataSource)
    {
        super(dataSource);
    }

}
</code>```

Body:
When i define more than one datasource in my spring cloud task application , it throws an exception. This is how i have defined the datasources

@Primary
@Bean(name="datasource1")
@ConfigurationProperties(prefix="spring.datasource")
public javax.sql.DataSource primaryDataSource() {
    return  DataSourceBuilder.create().build();
}

@Bean(name="datasource2")
@ConfigurationProperties(prefix="spring.datasource1")
public javax.sql.DataSource primaryDataSource1() {
    return  DataSourceBuilder.create().build();
}

@Bean
public TaskConfigurer taskConfigurer() {
    return new DefaultTaskConfigurer(primaryDataSource());
}

I have seen suggestions to put @Primary , defining TaskConfigurer like above, but none of them is working.Has any one faced this kind of problem ?

Thanks,
Neel

Body:
You need to override DefaultTaskConfigurer

@Configuration
public class BatchConfigurer extends DefaultTaskConfigurer
{

    public BatchConfigurer(@Qualifier("batchDataSource") DataSource dataSource)
    {
        super(dataSource);
    }

}


问:
magic 360 product view doesn't take more then 30 pics? How to pass img src as a parameter so that it takes more then 60 images to 360 rotate?
I have an HTML and JavaScript mixed code snippet which is using a plugin called magicbox 360 toolkit, but it won't take more than 30 images even when there are many pics present in the folder. I tried their documentation; nothing seems to work.</p>

```<code><div class="app-figure" id="zoom-fig">
    <!--    <a id="spin-1" class="Magic360" data-options="rows:55; columns:55"-->
    <!--        href="images\armani-bag\armani-bag-small-01-01.jpg">-->
    <!--    <img src="images\armani-bag\armani-bag-small-01-01.jpg"></a>-->

    <!-- <a id="spin-1" class="Magic360" data-options="rows:55; columns:55 "> <img src="images\armani-bag\p-01.jpg"></a> -->
    <a class="Magic360" data-options="filename:p-01-{row}-{col}.jpg; rows:4; columns:12;"><img src="images\armani-bag\p-01.jpg""/></a></div>
</code>```

答:
In your code, the first spin image is p-01.jpg. This does not match the filename descriptor, which is p-01-{row}-{col}.jpg.

Without knowing the file names of your images, I guess the answer is:

Either the descriptor should be p-{col}.jpg.

Or the first image should be something like p-01-01-01.jpg.

What are the file names of your images?


问:
Photo Library and Camera are accessible after permission got denied
I'm currently working on an app where I need to access either the photo library or the camera (or even both, it's up to the user).

If I close the app and deny the access to both camera and library for the app.

After restarting my App, it's still possible to access both, I can open and use the camera or even pick a photo from the library.
How is this possible, I thought Apple would restrict the access.

答:
Okay I know the answer...
I just didn't get the concept.
If I deny the access to the photoLibrary it is not possible to save images but, if Camera access is granted I can still use the photoLibrary.
If camera access is denied, I still get the alert with the context from the info.plist </p>


问:
C++ arguments changing while running
I've a very simple function that should read a txt file and return all lines by one vector of the type string. I've stepped trough it quite a few times with the debugger and the only thing i've noticed is that the value of "fileName" changes on the line of the ifstream declaration. What am i doing wrong?? Thx.

```<code>vector<string> readFile(char* fileName)
{
    vector<string> fileLines;
    fileLines.clear();
    string line;
    ifstream myfile (fileName);
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            fileLines.push_back(line);
        }
        myfile.close();
    }
    return fileLines;
}
</code>```

//////////////////////////////////

I have this function that should return the filenames of all txt files in the current directory.

```<code>   vector<char*> getFileList()
    {
        vector<char*> fileNames;
        fileNames.clear();
        WIN32_FIND_DATA FindFileData;
        HANDLE hFind = INVALID_HANDLE_VALUE;
        char currentPath[_MAX_PATH];
        getCurrentPath(currentPath);
        strncat(currentPath, "\\*", 3);
        if (hFind = FindFirstFile(currentPath, &FindFileData))
        {

            string fileExtension = getExt(FindFileData.cFileName);
            if (fileExtension == "txt" || fileExtension == "TXT")
            {
                fileNames.push_back(FindFileData.cFileName);
            }
            while(FindNextFile(hFind, &FindFileData) != 0)
            {
                string fileExtension = getExt(FindFileData.cFileName);
                if (fileExtension == "txt" || fileExtension == "TXT")
                    fileNames.push_back(FindFileData.cFileName);
            }
        }
        return fileNames;
    }
</code>```

That's how the function is going to be called:

```<code>vector<char*> inputFileList = getFileList();
if (inputFileList.size() > 0)
{
    for (int a=0; a<inputFileList.size(); a++)
    {
        fileLines = readFile(inputFileList[a]);
    }
}
</code>```

答:
My bet would be that you get your filename from a function which returns a pointer to a local variable, e.g. something like this:

```<code>char * getFilename() {
 char Filename[100] = "/foo";
 return Filename;
}
</code>```

The above isn't valid - Filename contents are on stack, and will be invalidated when getFilename() returns. vector<string> fileLines; will be located in the same memory, and therefore the data fileName points to will change when you step over the vector constructor.

EDIT: See e.g. C++ compiler warning - returning local variable for more information on this

Title: C++ arguments changing while running

Body:
I've a very simple function that should read a txt file and return all lines by one vector of the type string. I've stepped trough it quite a few times with the debugger and the only thing i've noticed is that the value of "fileName" changes on the line of the ifstream declaration. What am i doing wrong?? Thx.

vector<string> readFile(char* fileName)
{
    vector<string> fileLines;
    fileLines.clear();
    string line;
    ifstream myfile (fileName);
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            fileLines.push_back(line);
        }
        myfile.close();
    }
    return fileLines;
}

//////////////////////////////////

I have this function that should return the filenames of all txt files in the current directory.

   vector<char*> getFileList()
    {
        vector<char*> fileNames;
        fileNames.clear();
        WIN32_FIND_DATA FindFileData;
        HANDLE hFind = INVALID_HANDLE_VALUE;
        char currentPath[_MAX_PATH];
        getCurrentPath(currentPath);
        strncat(currentPath, "\\*", 3);
        if (hFind = FindFirstFile(currentPath, &FindFileData))
        {

            string fileExtension = getExt(FindFileData.cFileName);
            if (fileExtension == "txt" || fileExtension == "TXT")
            {
                fileNames.push_back(FindFileData.cFileName);
            }
            while(FindNextFile(hFind, &FindFileData) != 0)
            {
                string fileExtension = getExt(FindFileData.cFileName);
                if (fileExtension == "txt" || fileExtension == "TXT")
                    fileNames.push_back(FindFileData.cFileName);
            }
        }
        return fileNames;
    }

That's how the function is going to be called:

vector<char*> inputFileList = getFileList();
if (inputFileList.size() > 0)
{
    for (int a=0; a<inputFileList.size(); a++)
    {
        fileLines = readFile(inputFileList[a]);
    }
}

Body:
My bet would be that you get your filename from a function which returns a pointer to a local variable, e.g. something like this:

char * getFilename() {
 char Filename[100] = "/foo";
 return Filename;
}

The above isn't valid - Filename contents are on stack, and will be invalidated when getFilename() returns. vector<string> fileLines; will be located in the same memory, and therefore the data fileName points to will change when you step over the vector constructor.

EDIT: See e.g. C++ compiler warning - returning local variable for more information on this


问:
Customising the ID used in Marshmallow URLFor
I am using a Sqlite database, and flask, marshmallow, sqlalchemy to serve as a web api for a front end project.
I'm using a UUID stored as a blob in the database, and trying to stylise the data when its returned to the calling code.
I can convert the Id when its returned in the model using marshmallow's Function field, but using the HyperLinks, the Id is still being output as a byte array string:

```<code>class Item(Base):
    __tablename__ = 'Items'

    Id = Column(LargeBinary, primary_key=True)

    def __repr__(self):
        return '<Item {}>'.format(self.Name)

class ItemSchema(ma.Schema):
    Id = fields.Function(lambda obj: str(UUID(bytes=obj.Id)))
    _links = ma.Hyperlinks(
        {"url": ma.URLFor("item_detail", id="<Id>"), "collection": ma.URLFor("items")}
    )
    class Meta:
        fields = ("_links", "Id")
</code>```

Is there a way to format the < Id > that is output in the links?
i.e

```<code>{"url": ma.URLFor("item_detail", id="<str(UUID(bytes=Id))>"), "collection": ma.URLFor("items")}
</code>```

Here's how it is currently output:

```<code>{"_links": {"url": "/api/items/b%27%5Cx86%5Cxacx__%5Cxf9%5Cxc2J%5Cx80a6%5Cxa7%5Cx95%5Cx10%5Cx91%5Cxff%27", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}
</code>```

I want it to look like:

```<code>{"_links": {"url": "/api/items/86ac785f-5ff9-c24a-8061-36a7951091ff", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}
</code>```

I want the link to use the UUID format, not the byte array.

答:
I found out the way around this. It was with the model set up and not marshmallow.
As the database was/is storing the pk as a blob, I was able to use SQLAlchemy_utils UUID column, setting the binary to true, and it all worked:</p>

```<code>from sqlalchemy_utils import UUIDType
from uuid import UUID
....
Id = Column(UUIDType(binary=True), primary_key=True)
</code>```

Body:
I am using a Sqlite database, and flask, marshmallow, sqlalchemy to serve as a web api for a front end project.
I'm using a UUID stored as a blob in the database, and trying to stylise the data when its returned to the calling code.
I can convert the Id when its returned in the model using marshmallow's Function field, but using the HyperLinks, the Id is still being output as a byte array string:

class Item(Base):
    __tablename__ = 'Items'

    Id = Column(LargeBinary, primary_key=True)

    def __repr__(self):
        return '<Item {}>'.format(self.Name)

class ItemSchema(ma.Schema):
    Id = fields.Function(lambda obj: str(UUID(bytes=obj.Id)))
    _links = ma.Hyperlinks(
        {"url": ma.URLFor("item_detail", id="<Id>"), "collection": ma.URLFor("items")}
    )
    class Meta:
        fields = ("_links", "Id")

Is there a way to format the < Id > that is output in the links?
i.e

{"url": ma.URLFor("item_detail", id="<str(UUID(bytes=Id))>"), "collection": ma.URLFor("items")}

Here's how it is currently output:

{"_links": {"url": "/api/items/b%27%5Cx86%5Cxacx__%5Cxf9%5Cxc2J%5Cx80a6%5Cxa7%5Cx95%5Cx10%5Cx91%5Cxff%27", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}

I want it to look like:

{"_links": {"url": "/api/items/86ac785f-5ff9-c24a-8061-36a7951091ff", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}

I want the link to use the UUID format, not the byte array.

Body:
I found out the way around this. It was with the model set up and not marshmallow.
As the database was/is storing the pk as a blob, I was able to use SQLAlchemy_utils UUID column, setting the binary to true, and it all worked:

from sqlalchemy_utils import UUIDType
from uuid import UUID
....
Id = Column(UUIDType(binary=True), primary_key=True)


答:
*args in def __init__(self, *args): will lead self.args to store a tuple so the first if-statement will always be False. If you want your code to work, you should rewrite it as:

```<code>class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):
        if self.args == ('ti',):
            print('ti')
        elif len(self.args) == 1 and len(self.args[0]) == 1:
            print('it is a list with len 1 values')
        else:
            print('full list')

my_class = MyClass('ti')
my_class.test_meth()
</code>```

or with more generic (works with any iterable args):

```<code>class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):
        if len(self.args) == 1 and self.args[0] == 'ti':
            print('ti')
        elif len(self.args) == 1 and len(self.args[0]) == 1:
            print('it is a list with len 1 values')
        else:
            print('full list')

my_class = MyClass('ti')
my_class.test_meth()
</code>```

Title: Check the content of *args in a Class __init__

Body:
*args in def __init__(self, *args): will lead self.args to store a tuple so the first if-statement will always be False. If you want your code to work, you should rewrite it as:

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):
        if self.args == ('ti',):
            print('ti')
        elif len(self.args) == 1 and len(self.args[0]) == 1:
            print('it is a list with len 1 values')
        else:
            print('full list')

my_class = MyClass('ti')
my_class.test_meth()

or with more generic (works with any iterable args):

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):
        if len(self.args) == 1 and self.args[0] == 'ti':
            print('ti')
        elif len(self.args) == 1 and len(self.args[0]) == 1:
            print('it is a list with len 1 values')
        else:
            print('full list')

my_class = MyClass('ti')
my_class.test_meth()


问:
how to evaluate sql query using RelNode object
I am trying to convert sql query to Tinkerpop Gremlin. sql2Gremlin library does it but it looks on join as relation while I am relying on no join approach where you can refer relations with dot as delimiter between two entity.

I have parsed and validated query and I have RelRoot object.

Apache calcite returns RelRoot object which is root of algebraic expression.

Lets say I dont want to apply any query optimization, How do i use my RelNode Visitor to transform the RelRoot into TinkerPop Gremlin DSL.

Ideally I would first use From clause and then apply filters defined in where clause? How is select, filters, From clause represent in RelRoot tree?

What does apache calcite means by relational expression or RelNode?

Rephrasing the same question without TinkerPop Gremlin context:
How should I use RelRoot visitor to visit the RelRoot and transform the query to another DSL?

答:
I don't know why you insist on RelRoot and not RelNode tree, but Apache Calcite is doing its optimizations of relational algebra in RelNode stack. There is a class called RelVisitor that you might find interesting, since it can do exactly what you need: visit all RelNodes. You can then extract information you need from them and build your DSL with it.

EDIT:  In RelVisitor, you have access to the parent node and the child nodes of the currently visited node. You can extract all the information usually available to the RelNode object (see docs), and if you cast it to specific relational algebra operation, for example, Project, you can extract what fields are inside Project operation by doing node.getRowType().getFieldList().forEach(field -> names.add(field.getName())), where names is a previously defined Set<String>. You can find the full code here.

You should also take a look at the algebra docs to understand how SQL maps to relational algebra in Calcite before attempting this.


问:
Android - ViewPager is not showing the fragments
I am using a tablayout inside a fragemnt, the TabLayout has two fragments: one is showing a calendar and the other is just a simple plain text, I can switch between tabs correctly with out triggering any error, the problem is the content (inner fragments) are not showing, they are just "not there"!

I tried looking into other threads on StackoverFlow that has the same issue, but most of them they are facing problems with NPEs (Null pointer exceptions) errors, which is not my case.

I tried using: getChildFragmentManager() and getFragmentManager() instead of getSupportFragmentManager()

Please keep in mind that I am working with Nested fragments(fragments in a fragment)

I am using the documentation of AndroidHive and I have used it before but with simple fragments not nested one, it works perfectly

I tried using the Layout Inspector tool.

Q: What am I missing and what should I do to get it up and running?!

Here's my code so far:

XML: MainFragment

```<code><LinearLayout
   android:orientation="vertical"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
   <android.support.design.widget.TabLayout
       android:id="@+id/tabs"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabMode="fixed"
       app:tabGravity="fill"/>
       <android.support.v4.view.ViewPager
           android:id="@+id/viewpager"
           android:layout_height="match_parent"
           android:layout_width="match_parent"
           app:layout_behavior="@string/appbar_scrolling_view_behavior">
       </android.support.v4.view.ViewPager>
</LinearLayout>
</code>```

XML: Calendar fragment

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:animateLayoutChanges="true"
    android:id="@+id/main_content"
    tools:context=".Tabs.CalendarTab">
    <com.github.sundeepk.compactcalendarview.CompactCalendarView
        android:visibility="visible"
        android:id="@+id/compact_calendar"
        android:layout_width="match_parent"
        android:paddingRight="6dp"
        android:paddingLeft="6dp"
        android:layout_height="250dp"
        app:compactCalendarTargetHeight="250dp"
        app:compactCalendarTextSize="12sp"
        app:compactCalendarBackgroundColor="@color/colorWhite"
        app:compactCalendarTextColor="@color/colorDarkGrey"
        app:compactCalendarCurrentDayBackgroundColor="@color/color13"
        app:compactCalendarMultiEventIndicatorColor="@color/textColor2"
        app:compactCalendarShouldSelectFirstDayOfMonthOnScroll="true"
        app:compactCalendarCurrentDayIndicatorStyle="fill_large_indicator"/>
</RelativeLayout>
</code>```

XML List fragment

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Tabs.FullListTab">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 2"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
</code>```

MainFragment JAVA

```<code>private TabLayout tabLayout;
private ViewPager viewPager;

//onCreate Method:
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
/*** end onCreate() ***/

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new CalendarTab(), "Calendar");
    adapter.addFragment(new FullListTab(), "List");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

答:
I managed to solve this issue by using a third party library called SPager here's the Github link for full documentation. SPager does not use an adapter and it's easier and faster to implement.

HOWEVER I AM STILL LOOKING FOR A ANOTHER WAY WITHOUT USING A THIRD PARTY LIBRARY

This is what I practically did (as mentioned in their Github):

Implementation

```<code>implementation 'com.github.alfianyusufabdullah:spager:1.2.0'
</code>```

in the XML layout file

```<code><com.alfianyusufabdullah.SPager
   android:id="@+id/mPager"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />
</code>```

in my JAVA class

```<code>private SPager myViewPager;

//...

myViewPager = view.findViewById(R.id.mPager);

//...

myViewPager.initFragmentManager(getChildFragmentManager());
myViewPager.addPages("Inner fragment 1", new IFragOne());
myViewPager.addPages("Inner fragment 2", new IFragTwo());
myViewPager.build();
</code>```

IF you are using a tabLayout you can bind it with SPager like so:

```<code>myViewPager.addTabLayout(tabLayout);
</code>```

I should also mention that SPager is compatible with Kotlin

I decided to post, it might be useful to others, for my case this is a temporary fix until, someone answers this thread!

Body:
I am using a tablayout inside a fragemnt, the TabLayout has two fragments: one is showing a calendar and the other is just a simple plain text, I can switch between tabs correctly with out triggering any error, the problem is the content (inner fragments) are not showing, they are just "not there"!

I tried looking into other threads on StackoverFlow that has the same issue, but most of them they are facing problems with NPEs (Null pointer exceptions) errors, which is not my case.

I tried using: getChildFragmentManager() and getFragmentManager() instead of getSupportFragmentManager()

Please keep in mind that I am working with Nested fragments(fragments in a fragment)

I am using the documentation of AndroidHive and I have used it before but with simple fragments not nested one, it works perfectly

I tried using the Layout Inspector tool.

Q: What am I missing and what should I do to get it up and running?!

Here's my code so far:

XML: MainFragment

<LinearLayout
   android:orientation="vertical"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
   <android.support.design.widget.TabLayout
       android:id="@+id/tabs"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabMode="fixed"
       app:tabGravity="fill"/>
       <android.support.v4.view.ViewPager
           android:id="@+id/viewpager"
           android:layout_height="match_parent"
           android:layout_width="match_parent"
           app:layout_behavior="@string/appbar_scrolling_view_behavior">
       </android.support.v4.view.ViewPager>
</LinearLayout>

XML: Calendar fragment

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:animateLayoutChanges="true"
    android:id="@+id/main_content"
    tools:context=".Tabs.CalendarTab">
    <com.github.sundeepk.compactcalendarview.CompactCalendarView
        android:visibility="visible"
        android:id="@+id/compact_calendar"
        android:layout_width="match_parent"
        android:paddingRight="6dp"
        android:paddingLeft="6dp"
        android:layout_height="250dp"
        app:compactCalendarTargetHeight="250dp"
        app:compactCalendarTextSize="12sp"
        app:compactCalendarBackgroundColor="@color/colorWhite"
        app:compactCalendarTextColor="@color/colorDarkGrey"
        app:compactCalendarCurrentDayBackgroundColor="@color/color13"
        app:compactCalendarMultiEventIndicatorColor="@color/textColor2"
        app:compactCalendarShouldSelectFirstDayOfMonthOnScroll="true"
        app:compactCalendarCurrentDayIndicatorStyle="fill_large_indicator"/>
</RelativeLayout>

XML List fragment

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Tabs.FullListTab">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 2"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

MainFragment JAVA

private TabLayout tabLayout;
private ViewPager viewPager;

//onCreate Method:
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
/*** end onCreate() ***/

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new CalendarTab(), "Calendar");
    adapter.addFragment(new FullListTab(), "List");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Body:
I managed to solve this issue by using a third party library called SPager here's the Github link for full documentation. SPager does not use an adapter and it's easier and faster to implement.

HOWEVER I AM STILL LOOKING FOR A ANOTHER WAY WITHOUT USING A THIRD PARTY LIBRARY

This is what I practically did (as mentioned in their Github):

Implementation

implementation 'com.github.alfianyusufabdullah:spager:1.2.0'

in the XML layout file

<com.alfianyusufabdullah.SPager
   android:id="@+id/mPager"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

in my JAVA class

private SPager myViewPager;

//...

myViewPager = view.findViewById(R.id.mPager);

//...

myViewPager.initFragmentManager(getChildFragmentManager());
myViewPager.addPages("Inner fragment 1", new IFragOne());
myViewPager.addPages("Inner fragment 2", new IFragTwo());
myViewPager.build();

IF you are using a tabLayout you can bind it with SPager like so:

myViewPager.addTabLayout(tabLayout);

I should also mention that SPager is compatible with Kotlin

I decided to post, it might be useful to others, for my case this is a temporary fix until, someone answers this thread!


问:
Cannot cast cell as Custom cell
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

```<code>func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }
</code>```

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

```<code>import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}
</code>```

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard

答: Please check cell is nil or not. If cell is nil then remove .xib file from the target and add once again.

Title: Cannot cast cell as Custom cell

Body:
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard


问:
Combining reflection, enums and generics in Kotlin, type inference fails, but I don't know it as well
I'm using reflection to load an Enum class I'm using to integrate with an existing Java application.
In Java this is written as (in a class ValueUtil):

```<code>static <E extends Enum<E>> Class<E> getEnumType(String typeAsString) { ..reflection stuff.. }
</code>```

In Kotlin I try to use the result of this method.

```<code>private fun createEnumParameter(type: String, value: String, id: String?): EnumParameter<*> {
    val clazz = getEnumType(type)
    return createParam(clazz, value, id)
}

private fun <E: Enum<E>> getEnumType(type: String): Class<E> {
    return ValueParseUtil.getEnumType<E>(type)
}

private fun createParam(...): ... { ... }
</code>```

However, the compiler states:
Type inference error

So I try as best as I can to specify what I know (Enum<*>):
Enum<*> error

This fails due to enum recursion in the generics (which I/Kotlin/Java need(s) by the way).

Is reflection + enums + generics a recipe for compiler errors?

Any suggestions how to fix this?

答:
When concrete recursive generic type is unknown, you can emulate raw types by suppressing this error:</p>

```<code>@Suppress("UPPER_BOUND_VIOLATED")
val clazz = getEnumType<Enum<*>>(type)
</code>```

Body:
I'm using reflection to load an Enum class I'm using to integrate with an existing Java application.
In Java this is written as (in a class ValueUtil):

static <E extends Enum<E>> Class<E> getEnumType(String typeAsString) { ..reflection stuff.. }

In Kotlin I try to use the result of this method.

private fun createEnumParameter(type: String, value: String, id: String?): EnumParameter<*> {
    val clazz = getEnumType(type)
    return createParam(clazz, value, id)
}

private fun <E: Enum<E>> getEnumType(type: String): Class<E> {
    return ValueParseUtil.getEnumType<E>(type)
}

private fun createParam(...): ... { ... }

However, the compiler states:
Type inference error

So I try as best as I can to specify what I know (Enum<*>):
Enum<*> error

This fails due to enum recursion in the generics (which I/Kotlin/Java need(s) by the way).

Is reflection + enums + generics a recipe for compiler errors?

Any suggestions how to fix this?

Body:
When concrete recursive generic type is unknown, you can emulate raw types by suppressing this error:

@Suppress("UPPER_BOUND_VIOLATED")
val clazz = getEnumType<Enum<*>>(type)


答:
Do you need to make the virtual env?
if all the requirements are on the local machine call the py file from the python path</p>

Title: Is this possible: Cloning virtual environments to each users laptops while source code and related files remain in a network drive

Body:
I've written a model.py script which takes in a csv file, runs a bunch of calculations, then outputs the data into my Dashboard.xlsm file. All of these files are in the same folder in a shared network drive. This .py script needs to be able to be run by clicking a button within the xlsm file. To set this up, I've written a simple VBA macro (linked to the aforementioned button) which runs a .bat file. This .bat file contains shell commands to create a virtual environment in the same folder as my files, and then run my .py script within this venv.

However, activating this venv takes a long time (~ 1 min). If instead I setup a venv in a local folder, I believe it would speed up the runtime considerably.

Top level question: Is my current setup the best way for each user to be able to run my model.py file from within excel, if not, what alternatives are possible?

Mid level question: Is cloning a venv, one on each users laptop, the way to go to speed up my code's runtime, if not, what else could I try to do?

Code specific question: What is the best way to create cloned venv, and ensure each user will run my model.py file from within their own local venv?

My answer to the top level question:

I've spent the better part of the past 2 weeks looking into alternatives. I've tried transforming my .py file into an .exe, but neither myself, nor a colleague of mine were able to get the executable file to run properly (we tried using Pyinstaller and Py2exe).

I then looked into virtual environments, and, through lots of trial and error, finally got a working prototype (but just working for me for now).

My answer to the mid level question:

I honestly don't know and am unsure what to even google to find the answer to this.

My answer to the specific question:

I thought I could do the following to (hopefully) speed up the process:

Instead of saving the venv in the network folder, I would save/create n versions of the venv, one on each user's laptop (in a folder they wouldn't modify).

I create n .bat files, one for each user's specific path information. This is the file which, when run, creates the venv and runs the python script.

In my simple VBA macro, I check which user is using the xlsm file, and activate the correct .bat file accordingly.

Here is what I've coded so far:

The VBA script which calls the bat file

Sub run_model()

    Dim folderPath As String
    Dim shellCommand As String

    ActiveSheet.EnableCalculation = False
    ActiveSheet.EnableCalculation = True

    ActiveWorkbook.save

    folderPath = Application.ActiveWorkbook.Path
    shellCommand = folderPath & "\" & "USER_NAME_GOES_HERE.bat"
    Call Shell(shellCommand, vbNormalFocus)

End Sub

the bat file which sets up the venv and runs the py script

chdir I:\NETWORK_PATH
I:

python -m venv venv/
"./venv/Scripts/activate.bat" & pip install -r ./src/requirements.txt & "./venv/Scripts/activate.bat" & python "./src/MODEL.py"
'''

the python script

import USER_DEFINED_MODULE #this .py file contains functions I use later on in my script
import other_stuff

do stuff then output to dashboard.xlsm

Some final details:

no one has admin rights,

everyone has python installed via anaconda,

I tried installing python independently, but I was unable to make it functional (thus the fallback to the Anaconda distribution),

Yes, I have to use Excel as both the input/output files.


问:
"Count where" in a collection
Using lodash, what would be a good way to count the number of objects in a collection conditionally? Say I wanted to count the number of objects where

```<code>a < 4
</code>```

in the following collection

```<code>[{a : 1}, {a : 2}, {a : 3}, {a : 4}, {a : 5}, {a : 6}]
</code>```

答:
You can use _.countBy:

const count = _.countBy(arr, o => o.a < 4).true

Title: "Count where" in a collection

Body:
Using lodash, what would be a good way to count the number of objects in a collection conditionally? Say I wanted to count the number of objects where

a < 4

in the following collection

[{a : 1}, {a : 2}, {a : 3}, {a : 4}, {a : 5}, {a : 6}]


问:
How can i add class for div inside of javascript function
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name, ADRESS_TEXT and  phone  How can I do this

```<code>  function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                       //HERE     "<div class ="xxx" style='border-style:ridge' ><strong>Agency Name :</strong>  " + agency.agency_name + "<br>" +
                            "<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
                            "<strong>Phone :</strong>  " + agency.phone + "<br></div>"
                        );
                    });
                }
</code>```

CSS

```<code>.xxx{
    width: 220px;
    padding: 10px;
    border: 5px solid gray;
    margin: 0px;
}
</code>```

答:
As others said there is two ways: .addClass('classname1 classname2') and .attr('class','classname1 classname2') but addClass is better

in your case will be like:

```<code>function jsFilt(value) {
  console.log('running jsFilt');
  //document.getElementById("myDiv").innerHTML = "";
  $('#myDiv').html(''); // this is jquery way of doing it
  console.log('myDiv is now empty');

  value.AGENCY.forEach(agency => {
    console.log('inside loop');
        //first we create that div and give it class and style
        const $div = $('<div></div>').addClass('xxx').attr('style','border-style:ridge;');
        // here we set innerHTML
        $div.html(`
            <strong>Agency Name :</strong>  ` + agency.agency_name + `<br>
            <strong>Adress : </strong> ` + agency.ADRESS_TEXT + `<br>
            <strong>Phone :</strong> ` + agency.phone + `<br>
        `);

        console.log('here is the div we created:',$div);

        // here we append it to the container (#myDiv)
        $("#myDiv").append($div);
        console.log('this is how myDiv looks like now', $("#myDiv"));
    });
}
</code>```

make sure you call the function of course jsFilt(someValue)

I put some console.log('bla bla') in my codes if you open browser console you can see some messages being printed out and it helps you track issue. after everything worked you can remove console.log()s

So this may work or may have some syntax errors. Let me know if you could get it to work

Body:
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name, ADRESS_TEXT and  phone  How can I do this

  function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                       //HERE     "
Agency Name :  " + agency.agency_name + "
" +
                            "Adress :  " + agency.ADRESS_TEXT + "
 "+
                            "Phone :  " + agency.phone + "

"
                        );
                    });
                }

CSS

.xxx{
    width: 220px;
    padding: 10px;
    border: 5px solid gray;
    margin: 0px;
}

Body:
As others said there is two ways: .addClass('classname1 classname2') and .attr('class','classname1 classname2') but addClass is better

in your case will be like:

function jsFilt(value) {
  console.log('running jsFilt');
  //document.getElementById("myDiv").innerHTML = "";
  $('#myDiv').html(''); // this is jquery way of doing it
  console.log('myDiv is now empty');

  value.AGENCY.forEach(agency => {
    console.log('inside loop');
        //first we create that div and give it class and style
        const $div = $('<div></div>').addClass('xxx').attr('style','border-style:ridge;');
        // here we set innerHTML
        $div.html(`
            <strong>Agency Name :</strong>  ` + agency.agency_name + `<br>
            <strong>Adress : </strong> ` + agency.ADRESS_TEXT + `<br>
            <strong>Phone :</strong> ` + agency.phone + `<br>
        `);

        console.log('here is the div we created:',$div);

        // here we append it to the container (#myDiv)
        $("#myDiv").append($div);
        console.log('this is how myDiv looks like now', $("#myDiv"));
    });
}

make sure you call the function of course jsFilt(someValue)

I put some console.log('bla bla') in my codes if you open browser console you can see some messages being printed out and it helps you track issue. after everything worked you can remove console.log()s

So this may work or may have some syntax errors. Let me know if you could get it to work


答:
The args with always be a tuple, not a list, even if there’s only 1 element:

You don’t need to check whether the self.args is a tuple/list:

```<code>def test_meth(self):
    if len(self.args) == 1 and 'ti' in self.args:
        print('ti')
    if self.args and len(self.args[0]) == 1:
        print('list with length 1 len values')
    else:
        print('full list')
</code>```

Body:
I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()

Body:
The args with always be a tuple, not a list, even if there’s only 1 element:

You don’t need to check whether the self.args is a tuple/list:

def test_meth(self):
    if len(self.args) == 1 and 'ti' in self.args:
        print('ti')
    if self.args and len(self.args[0]) == 1:
        print('list with length 1 len values')
    else:
        print('full list')


问:
Azure LetsEncrypt cannot access .well-known/acme-challenge for my function
I am trying to enable SSL for my azure function using the letsencrypt site-extension for azure as described here. I was following the instructions in that wiki and on this website.

However, I get an error when it tries to verify the website.

The error indicates that the acme-challenge page cannot be accessed (404).

This is my web.config under .well-known/:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <clear />
      <add name="ACMEStaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
    </handlers>
    <staticContent>
      <remove fileExtension="." />
      <mimeMap fileExtension="." mimeType="text/plain" />
    </staticContent>
  </system.webServer>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>
</code>```

Does anyone have any ideas on what could be going wrong?

答:
I figured it out:

Similar to KetanChawda-MSFT's answer, except the proxy needs to hit the api endpoint function that you create.

So here's the function:

```<code>// https://YOURWEBSITE.azurewebsites.net/api/letsencrypt/{code}

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string code, TraceWriter log)
{
    log.Info($"C# HTTP trigger function processed a request. {code}");

    var content = File.ReadAllText(@"D:\home\site\wwwroot\.well-known\acme-challenge\"+code);
    var resp = new HttpResponseMessage(HttpStatusCode.OK);
    resp.Content =  new StringContent(content, System.Text.Encoding.UTF8, "text/plain");
    return resp;
}
</code>```

And here's the proxy that hits that function when letsEncrypt tries to verify the acme challenge:

```<code>{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "LetsEncryptProxy": {
      "matchCondition": {
        "route": "/.well-known/acme-challenge/{code}"
      },
      "backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/{code}"
    }
  }
}
</code>```

Body:
I am trying to enable SSL for my azure function using the letsencrypt site-extension for azure as described here. I was following the instructions in that wiki and on this website.

However, I get an error when it tries to verify the website.

The error indicates that the acme-challenge page cannot be accessed (404).

This is my web.config under .well-known/:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <clear />
      <add name="ACMEStaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
    </handlers>
    <staticContent>
      <remove fileExtension="." />
      <mimeMap fileExtension="." mimeType="text/plain" />
    </staticContent>
  </system.webServer>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

Does anyone have any ideas on what could be going wrong?

Body:
I figured it out:

Similar to KetanChawda-MSFT's answer, except the proxy needs to hit the api endpoint function that you create.

So here's the function:

// https://YOURWEBSITE.azurewebsites.net/api/letsencrypt/{code}

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string code, TraceWriter log)
{
    log.Info($"C# HTTP trigger function processed a request. {code}");

    var content = File.ReadAllText(@"D:\home\site\wwwroot\.well-known\acme-challenge\"+code);
    var resp = new HttpResponseMessage(HttpStatusCode.OK);
    resp.Content =  new StringContent(content, System.Text.Encoding.UTF8, "text/plain");
    return resp;
}

And here's the proxy that hits that function when letsEncrypt tries to verify the acme challenge:

{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "LetsEncryptProxy": {
      "matchCondition": {
        "route": "/.well-known/acme-challenge/{code}"
      },
      "backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/{code}"
    }
  }
}


问:
(pytest) Why doesn't property mock work in fixture?
I have a class with some properties. In my test, I need to set up a fixture, and have the properties mocked. However, the patch only works in the fixture function, not when the fixture is called. Any idea how to fix this?

Here is the simplified version of the problem. Let's assume that this is my class Panda:

class Panda(object):
    def __init__(self, name):
        self.panda_name = name

    @property
    def name(self):
        return self.panda_name
```

<p>and this is my test</p>

<pre class="lang-py prettyprint-override"><code>import pytest
from unittest.mock import patch, PropertyMock
from tmp import Panda

@pytest.fixture
@patch(
    'tmp.Panda.name',
    new_callable=PropertyMock,
    return_value="yuanyuan")
def fixture_panda(mk_name):
    p = Panda("this name should not matter")
    print(p.name)  # print "yuanyuan"
    return p

def test_panda_fixture(fixture_panda):
    p = fixture_panda
    print(p.name)  # print "this name should not matter"
    # this test fails
    assert p.name == "yuanyuan"
</code>```

The first print function in fixture_panda would print yuanyuan, which means the propertyMock works as expected. However the 2nd print function in test_panda_fixture print this name should not matter, which means the propertyMock doesn't work here. Any idea why this happens and how to fix this?

答:
If you want to monkeypatch something in pytest, you can use their built-in fixture monkeypatch, which can be inserted into all fixtures with scope = function. Here is an example from my codebase:

```<code>@pytest.fixture(scope="function", autouse=True)
def no_jwt(monkeypatch):
  """Monkeypatch the JWT verification functions for tests"""
  monkeypatch.setattr("flask_jwt_extended.verify_jwt_in_request", lambda: print("Verify"))
</code>```

If I apply it to your example, I think something like this should work:

```<code>@pytest.fixture
def fixture_panda(monkeypatch, mk_name):
  monkeypatch.setattr('tmp.Panda.name', "yuanyuan")
  p = Panda("this name should not matter")
  print(p.name)  # print "yuanyuan"
  return p
</code>```

Body:
I have a class with some properties. In my test, I need to set up a fixture, and have the properties mocked. However, the patch only works in the fixture function, not when the fixture is called. Any idea how to fix this?

Here is the simplified version of the problem. Let's assume that this is my class Panda:

class Panda(object):
    def __init__(self, name):
        self.panda_name = name

    @property
    def name(self):
        return self.panda_name

and this is my test

import pytest
from unittest.mock import patch, PropertyMock
from tmp import Panda

@pytest.fixture
@patch(
    'tmp.Panda.name',
    new_callable=PropertyMock,
    return_value="yuanyuan")
def fixture_panda(mk_name):
    p = Panda("this name should not matter")
    print(p.name)  # print "yuanyuan"
    return p

def test_panda_fixture(fixture_panda):
    p = fixture_panda
    print(p.name)  # print "this name should not matter"
    # this test fails
    assert p.name == "yuanyuan"

The first print function in fixture_panda would print yuanyuan, which means the propertyMock works as expected. However the 2nd print function in test_panda_fixture print this name should not matter, which means the propertyMock doesn't work here. Any idea why this happens and how to fix this?

Body:
If you want to monkeypatch something in pytest, you can use their built-in fixture monkeypatch, which can be inserted into all fixtures with scope = function. Here is an example from my codebase:

@pytest.fixture(scope="function", autouse=True)
def no_jwt(monkeypatch):
  """Monkeypatch the JWT verification functions for tests"""
  monkeypatch.setattr("flask_jwt_extended.verify_jwt_in_request", lambda: print("Verify"))

If I apply it to your example, I think something like this should work:

@pytest.fixture
def fixture_panda(monkeypatch, mk_name):
  monkeypatch.setattr('tmp.Panda.name', "yuanyuan")
  p = Panda("this name should not matter")
  print(p.name)  # print "yuanyuan"
  return p


问:
R - How to create an arbitrary list of lists
I am trying to create a list of lists in R but the interior list are only being stored as temp variables as I go through a loop and when I try to access one of the sub-lists inside of the larger list, I only receive the first element of the sub-list.

I found this answer R. how make list of lists in R? but it is not working for me and I think it might be due to the fact that I am not storing each list.

Here is my code:

```<code>list1 <- list(1,2,3,4,5)
allLists <- list()
for(i in 1:5){
    allLists[i] = list1
}
newlst = allLists[[3]]
newlst[2]
#[[1]]
#NULL
</code>```

I wold like to be able to access all the lists within allLists but it does not let me. The value for newlst is 1 when I would like it to be the list (1,2,3,4,5)

答:
If we want to create a list of lists an option is replicate

```<code>replicate(5, list1, simplify = FALSE)
</code>```

Body:
I am trying to create a list of lists in R but the interior list are only being stored as temp variables as I go through a loop and when I try to access one of the sub-lists inside of the larger list, I only receive the first element of the sub-list.

I found this answer R. how make list of lists in R? but it is not working for me and I think it might be due to the fact that I am not storing each list.

Here is my code:

list1 <- list(1,2,3,4,5)
allLists <- list()
for(i in 1:5){
    allLists[i] = list1
}
newlst = allLists[[3]]
newlst[2]
#[[1]]
#NULL

I wold like to be able to access all the lists within allLists but it does not let me. The value for newlst is 1 when I would like it to be the list (1,2,3,4,5)

Body:
If we want to create a list of lists an option is replicate

replicate(5, list1, simplify = FALSE)


问:
Retrieving Classes of Beans prior/during instantiation phase
In an Spring Application it is possible to retrieve all (?) Beans with applicationContext.getBeansOfType(Object.class). This is of course only possible, after all Beans have been created.

So, if I call this method in the constructor of a Bean, I have to be lucky, to be the last Bean to be created, to have access to all of them.

As far as I understand the life cycle of Spring Beans, there is a phase in which BeanDefinitions are created, before the Beans are initialized.

How is it possible to retrive all created BeanDefinitions in the constructor of a Bean?

Can I also retrive the types (as Class) of those BeanDefinitions? The type BeanDefinition seems to only provide the "current bean class name of this bean definition".

Or is the only way to get those types after all Beans have been constructed (e.g. @PostConstruct)?

答:
Maybe this code could help

```<code>    for (String name : applicationContext.getBeanFactory().getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(name);
        String className = beanDefinition.getBeanClassName();
        Class<?> clazz = Class.forName(className);
    }
</code>```

The loop gets you all the BeanDefinitions and then you load the class for each and do what you want?

By the way this might not be a good way to use Spring but it will work.

Body:
Maybe this code could help

    for (String name : applicationContext.getBeanFactory().getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(name);
        String className = beanDefinition.getBeanClassName();
        Class<?> clazz = Class.forName(className);
    }

The loop gets you all the BeanDefinitions and then you load the class for each and do what you want?

By the way this might not be a good way to use Spring but it will work.