问:
Get Selected Radio Button WITHOUT a Submit button
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

```<code>document.getElementById("results").innerHTML = NONE or A or B
</code>```

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

```

答:
Here, I added a button so you can get the status when clicked. You should add a value attribute to your input fields.

$(document).ready(function(){
  $(".detect").click(function(){
    var radioValue = $("input[name='test']:checked").val();
    if(radioValue){
      $(".results").text(radioValue);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="NONE" autocomplete="off">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="A" value="A" autocomplete="off">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="B" value="B" autocomplete="off">B
  </label>
</div>

<div class="results"></div>
<button class="detect">Detect</button></code>```

Body:
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

document.getElementById("results").innerHTML = NONE or A or B

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

Body:
Here, I added a button so you can get the status when clicked. You should add a value attribute to your input fields.

$(document).ready(function(){
  $(".detect").click(function(){
    var radioValue = $("input[name='test']:checked").val();
    if(radioValue){
      $(".results").text(radioValue);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="NONE" autocomplete="off">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="A" value="A" autocomplete="off">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="B" value="B" autocomplete="off">B
  </label>
</div>

<div class="results"></div>
<button class="detect">Detect</button>


来源: stackexchange

问:
How to add listener to ul li list?
How to add listener to ul li list, that is in component template?

```<code><ul #list>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

I have tried:

```<code>@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}
</code>```

But it does not work for me.

答:
or you should add nativeElement in your example

```<code> list.nativeElement.addEventListener('keydown', this.onKeyDown);
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to add listener to ul li list?

Body:
How to add listener to ul li list, that is in component template?

1

2

3

I have tried:

@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}

But it does not work for me.

Body:
or you should add nativeElement in your example

 list.nativeElement.addEventListener('keydown', this.onKeyDown);


问:
How can we pass a hidden parameter with a url to a jsp through a GWT java file?
I want to pass a hidden parameter with a url to a jsp through a GWT java file.is this possible?
If yes then how?</p>

答:
If a JSP file is hosting your GWT module, then no, it's too late to pass a parameter to that JSP.

If your GWT module is causing a JSP to be loaded, then yes, you can pass parameters.  When you create your request, add a post parameter.  If you're using a form, add a Hidden widget: http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/ui/Hidden.html

ContentLicense: CC BY-SA 3.0


问:
Three.js Cannot read property 'uniforms' of undefined
I completely followed the translucency example(https://threejs.org/examples/?q=tran#webgl_materials_translucency), but i don't know why i failed.

" var uniforms = THREE.UniformsUtils.clone( shader.uniforms );" with this chrome said:  Uncaught TypeError: Cannot read property 'uniforms' of undefined.

Please help me ~~~
Just incase i put is all my code here.

```<code><html>
    <head>
        <meta charset="utf-8">
        <title> 1 </title>
        <style>
            body { margin: 0; }
            canvas { display: block; }
        </style>
    </head>
<body>
    <script type="module">
        import * as THREE from './js/three.module.js';
        import { OrbitControls } from './js/OrbitControls.js';
        import { TranslucentShader } from './js/TranslucentShader.js';

        let scene, camera, renderer;

    function init(){

        scene = new THREE.Scene();

        camera = new THREE.PerspectiveCamera(70,window.innerWidth/window.innerHeight,1,15000);
        camera.position.set(0,500,1000);

        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);

        var loader = new THREE.TextureLoader();
        var imgTexture = loader.load( 'white.jpg' );
        imgTexture.wrapS = imgTexture.wrapT = THREE.RepeatWrapping;
        var shader =  THREE.TranslucentShader;

        var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

        uniforms[ 'map' ].value = imgTexture;
        uniforms[ 'diffuse' ].value = new THREE.Vector3( 1.0, 0.2, 0.2 );
        uniforms[ 'shininess' ].value = 500;
        uniforms[ 'thicknessMap' ].value = imgTexture;
        uniforms[ 'thicknessColor' ].value = new THREE.Vector3( 0.5, 0.3, 0.0 );
        uniforms[ 'thicknessDistortion' ].value = 0.1;
        uniforms[ 'thicknessAmbient' ].value = 2;
        uniforms[ 'thicknessAttenuation' ].value = 1.2;
        uniforms[ 'thicknessPower' ].value = 3.0;
        uniforms[ 'thicknessScale' ].value = 10;

        var material = new THREE.ShaderMaterial( {
                uniforms: uniforms,
                vertexShader: shader.vertexShader,
                fragmentShader: shader.fragmentShader,
                lights: true
            } );
        material.extensions.derivatives = true;

        var geo = new THREE.BoxGeometry(100,100,100);
        var cube = new THREE.Mesh(geo,material);
        scene.add(cube);

        let control = new THREE.OrbitControls(camera, renderer.domElement);

        var light = new THREE.PointLight( 0xffffff,1 );
        scene.add(light);

    }

    function animate(){
        requestAnimationFrame(animate);
        renderer.render(scene,camera);
    }

    init();
    animate();

</script>

</body>
</html>
</code>```

coding is so hard

答:
When you import { TranslucentShader } at the top of your code, the example shows you have to access it as follows:

var shader = TranslucentShader;

No need to put THREE. in front of it. This is creating a reference to an undefined object.

Body:
I completely followed the translucency example(https://threejs.org/examples/?q=tran#webgl_materials_translucency), but i don't know why i failed.

" var uniforms = THREE.UniformsUtils.clone( shader.uniforms );" with this chrome said:  Uncaught TypeError: Cannot read property 'uniforms' of undefined.

Please help me ~~~
Just incase i put is all my code here.

        <meta charset="utf-8">
        <title> 1 </title>

coding is so hard


问:
I have an excel file. In which there are multiple columns and rows how does one filter the columns by the rows for ggplot
I have an excel file that has data as such:

I have to create a box plot and am using ggplot. How does one filter it such that the results for Lead will show based on what the Ward number is. For example if I say Ward==1 then it will show the results Lead 5.0, 7.8 and 6.3 and create a box plot with these . I am trying to create a geom_boxplot and stat_boxplot.

答:
You could subset your data then make your boxplot.

```<code>test <- data.frame(ID=c(1,2,3,4,5),Ward=c(1,1,2,3,1),Lead=c(5.0,7.8,3.6,2.8,6.3))
</code>```

The above code just creates sample data

```<code>  ID Ward Lead
1  1    1  5.0
2  2    1  7.8
3  3    2  3.6
4  4    3  2.8
5  5    1  6.3
</code>```

Subset the data

```<code>subset(test,test$Ward==1)
</code>```

This yeilds

```<code>  ID Ward Lead
1  1    1  5.0
2  2    1  7.8
5  5    1  6.3
</code>```

Body:
You could subset your data then make your boxplot.

test <- data.frame(ID=c(1,2,3,4,5),Ward=c(1,1,2,3,1),Lead=c(5.0,7.8,3.6,2.8,6.3))

The above code just creates sample data

  ID Ward Lead
1  1    1  5.0
2  2    1  7.8
3  3    2  3.6
4  4    3  2.8
5  5    1  6.3

Subset the data

subset(test,test$Ward==1)

This yeilds

  ID Ward Lead
1  1    1  5.0
2  2    1  7.8
5  5    1  6.3


问:
Find cycle in directed graph using BFS?
I thought about flagging all nodes that I visited. When I found some node that have flag set is it cycle. But this wont work because one node can have multiple parents and multiple child's. How can I do it to find cycle? </p>

<p>PS: I know that for finding cycle is more suitable DFS, but I need to do it by BFS.  </p>

答:
The answer above is correct but I think it is not a BFS or at least not an intuitive BFS. It mainly depends on checking the outgoing edges of each node and deleting the edges connected to the nodes without incoming edges. My answer may be a more intuitive BFS implementation on this problem.

Let’s think about what is cycle?

A node can find a path to reach himself, then there is a cycle.

Then why DFS can solve the finding cycle task while BFS can’t?

To find the cycle in a directed graph, we first come up with DFS: If there is a back edge in the DFS tree, then there will be cycle in the graph. When building up the DFS tree, we can record the starting counter and end counter for each node so that we can check if the pointing node is the current node’s ancestor. Once the back edge is found (pointing node is not finished but starts before current node), it means that the node can find a way back to one of its ancestors. While the BFS is used to fully explore one’s neighbors but can’t save the ancestors. So, maybe we can make BFS work on this problem if save the ancestors when go through the graph:

During the BFS, when each node explores its neighbors (or children),sends the accumulated ancestor information to their neighbors. When a node finds one of the ancestors passed from his parent is himself, then there is a cycle in the graph.
Here is a picture shows the step of this algorithm:

Step 1, A explores his neighbors: B, C, D, E and send the ancestor information {A} to them.

Step 2, B explores his neighbors E and send the ancestor information {A, B} to it.

Step 3, C explores his neighbors D, F and send ancestor information {A, C} to them.

Step 4, D finds no neighbors.

Step 5, F explores his neighbors D, G and send ancestor information {A, C, F} to them.

Step 6, G explores his neighbors C and send ancestor information {A, C, F, G} to it. Then C will find that his ancestor is himself, then there will be a cycle.

Then, how about the running time of this algorithm?  The running time of traditional BFS is Theta(V+E), but in this algorithm, passing and union of the ancestor information, will take total E steps, while in each step information array size is larger than 1 less than C*V. So the total running time is O(EV), Omega(V+E).

Title: Find cycle in directed graph using BFS?

Body:
I thought about flagging all nodes that I visited. When I found some node that have flag set is it cycle. But this wont work because one node can have multiple parents and multiple child's. How can I do it to find cycle?

PS: I know that for finding cycle is more suitable DFS, but I need to do it by BFS.


问:
How do I check present viewController or root viewController?
I have set up my class with UITabBarDelegate and implemented its method didSelectItem to detect when a certain tabBar item is pressed. Works great. In each tabBar item I have one containerView that can show a "you have to login"-page if the user is not logged in, and another containerView that present viewControllers that are embedded in a navigationController.

I would like to keep track of the viewController that is presented in the current tab item, and/or the root viewController of that tab.

I have tried a number of different approaches, but most of them return nil or I can't get it to work. I think the whole container situation makes it harder to handle.

It looks something like this:

```<code>@interface MyTabBarController () <UITabBarDelegate>

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {

    NSUInteger indexOfTab = [[tabBar items] indexOfObject:item];

    switch (indexOfTab) {
        case 0: {
            NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
            break;
        }
        case 1: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
        }
        case 2: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);

//These return nil
            NSLog(@"AAAAAA %@", ((UINavigationController*)_appD.window.rootViewController).visibleViewController);
            NSLog(@"AAAAAA %@", ((UITabBarController*)_appD.window.rootViewController).selectedViewController);
            NSLog(@"AAAAAA %@", self.navigationController.topViewController);
            NSLog(@"AAAAAA %@", self.navigationController.visibleViewController);

//This returns with a value, but can't get it to work with conditionals, that is, when I'm in root, the else is triggered
            NSLog(@"AAAAAA %@", self.tabBar.window.rootViewController);

            if(!self.tabBar.window.rootViewController) {
                NSLog(@"THIS IS NOT ROOT");

            }else {
                NSLog(@"this is ROOT");
            }

// This returns nil
            ((UINavigationController*)_appD.window.rootViewController).visibleViewController;
            ((UITabBarController*)_appD.window.rootViewController).selectedViewController;

            //Doesn't work
            if([self.navigationController.viewControllers[0] isKindOfClass:[ExperiencesListViewController class]]) {
                           NSLog(@"IS KIND OF CLASS LIST");
                       }
                       if([self.navigationController.viewControllers[0].childViewControllers isKindOfClass:[ExperiencesContainerViewController class]]) {
                           NSLog(@"IS KIND OF CLASS CONTAINER");
                     }
           break;
       }
        case 3: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        case 4: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        default:
            break;
    }
}

So, what else can I try? Seems like I have to use `self.tabBar.window.rootViewController` in some way, no?

***EDIT***
Oh, and I have tried the `tabBarController` delegate but that doesn't trigger. Also, the `tabBar` is constructed programmatically if that helps.

</code>```

答:
Sorry to have not read your question correctly. Here's what I suggest you do.

All of these view controllers that you're interested in keeping track of: you should have them send a custom notification from within their -viewDidAppear: (or -viewWillAppear:) method. Then let your ApolloTabBarController object register for that notification. When it gets the notification, you could then store a reference to the view controller. That reference will always point to the active view controller.

In your individual view controllers, do something like the following:

```<code>- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];

    [nc postNotificationName:@"XYZViewControllerDidBecomeActiveNotification"
                      object:self];
}
</code>```

Of course, you would want to use some kind of constant for the notification name.

In your ApolloTabBarController class, register for XYZViewControllerDidBecomeActiveNotification and implement something like:

```<code>- (void)viewControllerDidBecomeActive:(NSNotification *)notification
{
    self.activeViewController = [notification object];
}
</code>```

I hope that helps!

Body:
I have set up my class with UITabBarDelegate and implemented its method didSelectItem to detect when a certain tabBar item is pressed. Works great. In each tabBar item I have one containerView that can show a "you have to login"-page if the user is not logged in, and another containerView that present viewControllers that are embedded in a navigationController.

I would like to keep track of the viewController that is presented in the current tab item, and/or the root viewController of that tab.

I have tried a number of different approaches, but most of them return nil or I can't get it to work. I think the whole container situation makes it harder to handle.

It looks something like this:

@interface MyTabBarController () <UITabBarDelegate>

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {

    NSUInteger indexOfTab = [[tabBar items] indexOfObject:item];

    switch (indexOfTab) {
        case 0: {
            NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
            break;
        }
        case 1: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
        }
        case 2: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);

//These return nil
            NSLog(@"AAAAAA %@", ((UINavigationController*)_appD.window.rootViewController).visibleViewController);
            NSLog(@"AAAAAA %@", ((UITabBarController*)_appD.window.rootViewController).selectedViewController);
            NSLog(@"AAAAAA %@", self.navigationController.topViewController);
            NSLog(@"AAAAAA %@", self.navigationController.visibleViewController);

//This returns with a value, but can't get it to work with conditionals, that is, when I'm in root, the else is triggered
            NSLog(@"AAAAAA %@", self.tabBar.window.rootViewController);

            if(!self.tabBar.window.rootViewController) {
                NSLog(@"THIS IS NOT ROOT");

            }else {
                NSLog(@"this is ROOT");
            }

// This returns nil
            ((UINavigationController*)_appD.window.rootViewController).visibleViewController;
            ((UITabBarController*)_appD.window.rootViewController).selectedViewController;

            //Doesn't work
            if([self.navigationController.viewControllers[0] isKindOfClass:[ExperiencesListViewController class]]) {
                           NSLog(@"IS KIND OF CLASS LIST");
                       }
                       if([self.navigationController.viewControllers[0].childViewControllers isKindOfClass:[ExperiencesContainerViewController class]]) {
                           NSLog(@"IS KIND OF CLASS CONTAINER");
                     }
           break;
       }
        case 3: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        case 4: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        default:
            break;
    }
}

So, what else can I try? Seems like I have to use `self.tabBar.window.rootViewController` in some way, no?

***EDIT***
Oh, and I have tried the `tabBarController` delegate but that doesn't trigger. Also, the `tabBar` is constructed programmatically if that helps.

Body:
Sorry to have not read your question correctly. Here's what I suggest you do.

All of these view controllers that you're interested in keeping track of: you should have them send a custom notification from within their -viewDidAppear: (or -viewWillAppear:) method. Then let your ApolloTabBarController object register for that notification. When it gets the notification, you could then store a reference to the view controller. That reference will always point to the active view controller.

In your individual view controllers, do something like the following:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];

    [nc postNotificationName:@"XYZViewControllerDidBecomeActiveNotification"
                      object:self];
}

Of course, you would want to use some kind of constant for the notification name.

In your ApolloTabBarController class, register for XYZViewControllerDidBecomeActiveNotification and implement something like:

- (void)viewControllerDidBecomeActive:(NSNotification *)notification
{
    self.activeViewController = [notification object];
}

I hope that helps!


问:
chisquare test in r that keeps row names
I'm building an employee survey with two waves, and I want to make sure that each wave is balanced in terms of some demographic variables, such as ethnicity and gender. Here is a fictitious sample of the data:

```<code>library(tidyverse)
sample_data <- tibble(demographics = c("White / Female", "Non-White / Female", "White / Male", "Non-White / Male", "White / Transgender", "Non-White / Transgender"),
                      wave_1 = c(40, 38, 60, 56, 0, 2),
                      wave_2 = c(38, 39, 62, 58, 1, 0))
</code>```

If I run the chisq.test() on sample_data, I get an error:

```<code>library(stats)
chisq.test(sample_data)

Error in chisq.test(sample_data) :
  all entries of 'x' must be nonnegative and finite
</code>```

But I don't get the error if I just use the two count columns:

```<code>sample_data_count <- sample_data %>%
  dplyr::select(wave_1, wave_2)
chisq.test(sample_data_count)

    Pearson's Chi-squared test

data:  sample_data_count
X-squared = 3.1221, df = 5, p-value = 0.6812

Warning message:
In chisq.test(sample_data_count) :
  Chi-squared approximation may be incorrect
</code>```

I understand that R doesn't like that I have my demographics in the sample_data, but it's hard not having them in if I want to look at the observed values by various demographics. Is there a way to run the chisquare test with those row names in?

I saw an example using at http://www.sthda.com/english/wiki/chi-square-test-of-independence-in-r using this dataset (file_path <- "http://www.sthda.com/sthda/RDoc/data/housetasks.txt") that does do a chi square test in r with the row names still in it.

Any help would be appreciated!

答:
You can define your own function that runs the chi square on numeric columns only:

```<code> my_chi <- function(df) chisq.test(as.matrix(df[, sapply(df, is.numeric)]))
</code>```

So now you can do

```<code>my_chi(sample_data)
#>
#>  Pearson's Chi-squared test
#>
#> data:  as.matrix(df[, sapply(df, is.numeric)])
#> X-squared = 3.1221, df = 5, p-value = 0.6812
#>
#> Warning message:
#> In chisq.test(as.matrix(df[, sapply(df, is.numeric)])) :
#>   Chi-squared approximation may be incorrect
</code>```

Body:
I'm building an employee survey with two waves, and I want to make sure that each wave is balanced in terms of some demographic variables, such as ethnicity and gender. Here is a fictitious sample of the data:

library(tidyverse)
sample_data <- tibble(demographics = c("White / Female", "Non-White / Female", "White / Male", "Non-White / Male", "White / Transgender", "Non-White / Transgender"),
                      wave_1 = c(40, 38, 60, 56, 0, 2),
                      wave_2 = c(38, 39, 62, 58, 1, 0))

If I run the chisq.test() on sample_data, I get an error:

library(stats)
chisq.test(sample_data)

Error in chisq.test(sample_data) :
  all entries of 'x' must be nonnegative and finite

But I don't get the error if I just use the two count columns:

sample_data_count <- sample_data %>%
  dplyr::select(wave_1, wave_2)
chisq.test(sample_data_count)

    Pearson's Chi-squared test

data:  sample_data_count
X-squared = 3.1221, df = 5, p-value = 0.6812

Warning message:
In chisq.test(sample_data_count) :
  Chi-squared approximation may be incorrect

I understand that R doesn't like that I have my demographics in the sample_data, but it's hard not having them in if I want to look at the observed values by various demographics. Is there a way to run the chisquare test with those row names in?

I saw an example using at http://www.sthda.com/english/wiki/chi-square-test-of-independence-in-r using this dataset (file_path <- "http://www.sthda.com/sthda/RDoc/data/housetasks.txt") that does do a chi square test in r with the row names still in it.

Any help would be appreciated!

Body:
You can define your own function that runs the chi square on numeric columns only:

 my_chi <- function(df) chisq.test(as.matrix(df[, sapply(df, is.numeric)]))

So now you can do

my_chi(sample_data)
#>
#>  Pearson's Chi-squared test
#>
#> data:  as.matrix(df[, sapply(df, is.numeric)])
#> X-squared = 3.1221, df = 5, p-value = 0.6812
#>
#> Warning message:
#> In chisq.test(as.matrix(df[, sapply(df, is.numeric)])) :
#>   Chi-squared approximation may be incorrect


问:
Migration: No DbContext was found in assembly
Using VS Community 2017. I have tried to create initial migration with error message saying:

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework\Add-Migration' for Entity Framework 6.
  No DbContext was found in assembly 'Test_Project'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

... code in my dbcontext:

```<code>protected override void OnModelCreating(DbModelBuilder mb)
{
    base.OnModelCreating(mb);

    mb.Entity<Stuff>().ToTable("Stuff");

}

public DbSet<Stuff> Stuff{ get; set; }
</code>```

答: You have to specify the project name where the DbContext is located. So just right on the Nugget PM Console, type: Add-Migration MigrationName -Project YourProjectName.

Body:
Using VS Community 2017. I have tried to create initial migration with error message saying:

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework\Add-Migration' for Entity Framework 6.
  No DbContext was found in assembly 'Test_Project'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

... code in my dbcontext:

protected override void OnModelCreating(DbModelBuilder mb)
{
    base.OnModelCreating(mb);

    mb.Entity<Stuff>().ToTable("Stuff");

}

public DbSet<Stuff> Stuff{ get; set; }


问:
Javascript\JQuery function does not work without an alert
I have a problem with my 2 JQuery\Javascript functions. My problem is that when I dont have alerts in both my functions, both the functions don't work properly, and the event agument and eventtarget parameters are overwritten.

please advise on the solution for this.

```<code> function SubmitAdded() {

      $(document).ready(function (){
      var arrAdded = new Array();
      $('#JQAddedList li').each(function (i) {
          arrAdded[i] = $(this).text();
      });

          __doPostBack("AddActivity", arrAdded);
         // alert('if this alert is commented out, function does not work.');

 });
  }
</code>```

答:
// alert('Added ('if this alert is
  commented out, function does not
  work.');

You seem to have one parenthesis to many...

or as someone more intelligent than me said:

"It's not the parenthesis that there's one too many of, it's the excess quote. – Xhalent"

Body:
I have a problem with my 2 JQuery\Javascript functions. My problem is that when I dont have alerts in both my functions, both the functions don't work properly, and the event agument and eventtarget parameters are overwritten.

please advise on the solution for this.

 function SubmitAdded() {

      $(document).ready(function (){
      var arrAdded = new Array();
      $('#JQAddedList li').each(function (i) {
          arrAdded[i] = $(this).text();
      });

          __doPostBack("AddActivity", arrAdded);
         // alert('if this alert is commented out, function does not work.');

 });
  }


问:
how do I convert json data into Html tag?
I am trying to display JSON data in the Html tag. But I got the error:

Uncaught (in promise) TypeError.

async function fetchData() {
        const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
        const data = await response.json();
        console.log(data);

        document.getElementById("display").insertAdjacentText = `
        ${data.articles.map(function (article) {
            return `

${article.title}

${article.description}

${article.author}

${article.url} target="_blank">

             `
        }).join('')}`

    }
    fetchData();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="display"></div></code>```

答:
The problem is your div element is of class display, not id display, and thus document.getElementById("display") returns null. Change class="display" to id="display".

Also, use document.getElementById("display").innerHTML for this.


问:
How to show text in combobox when no item selected?
C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo "Please select item" in that situation.

Current implementation is just added empty item with such text on index 0 and remove it when user select one of following items. Unfortunately empty item is shown in dropdown list as well. How to avoid this situation or in other way - is there any way to show custom text on ComboBox when no item is selected?

Answers below work when ComboBoxStyle is set to DropDown (ComboBox is editable). Is there possibility to do this when ComboBoxStyle is set to DropDownList?

答:
Credit must be given to IronRazerz in a response to TextBox watermark (CueBanner) which goes away when user types in single line TextBox (not for RichTextBox).

You will need to declare the following in your class:

```<code>private const int CB_SETCUEBANNER = 0x1703;

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int msg, int wParam, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]string lParam);
</code>```

Then you can use it with something like:

```<code>SendMessage(this.comboBox1.Handle, CB_SETCUEBANNER, 0, "Please select an item...");
</code>```

This is assuming the Combo Box's DropDownStyle is set to DropDownList, as is the original poster's question.

This should result in something like the following:

Body:
Credit must be given to IronRazerz in a response to TextBox watermark (CueBanner) which goes away when user types in single line TextBox (not for RichTextBox).

You will need to declare the following in your class:

private const int CB_SETCUEBANNER = 0x1703;

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int msg, int wParam, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]string lParam);

Then you can use it with something like:

SendMessage(this.comboBox1.Handle, CB_SETCUEBANNER, 0, "Please select an item...");

This is assuming the Combo Box's DropDownStyle is set to DropDownList, as is the original poster's question.

This should result in something like the following:


问:
fix clicking html link when already at destination causing repeat folder in address bar
if i am at the current address: "pages/tasks.html"

then click a link that has:

Post Task

my address becomes:
"/pages/pages/task.html"

Is there any way i can just remove the entire address bar and put the info back? that would allow me to use a header.php template for all of my pages, even if they are in different folders.

答:
I think you should do that using ".." notation (which means a folder back) so like
Post Task

Another solution would be using an absolute path instead of local. So starting from the root directory of you pages like root/pages/task.html

Body:
I think you should do that using ".." notation (which means a folder back) so like <li><a href="./../tasks.html">Post Task</a></li>

Another solution would be using an absolute path instead of local. So starting from the root directory of you pages like root/pages/task.html


问:
problem with oracle connection in c#
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

```<code>//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}
</code>```

答:
```<code>try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
</code>```

You have pottential problem here: if conn.Open() fails (so connection is not opened) in finally you call conn.close(), but connection isn't opened - so it also fails, but it is now outside try catch. You need check for

```<code>if (Conn!=null && Conn.IsOpen())
  Conn.Close();
</code>```

Connection string for oracle:
Data Source=TORCL;User Id=myUsername;Password=myPassword;

Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

More here

Title: problem with oracle connection in c#

Body:
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}

Body:
try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }

You have pottential problem here: if conn.Open() fails (so connection is not opened) in finally you call conn.close(), but connection isn't opened - so it also fails, but it is now outside try catch. You need check for

if (Conn!=null && Conn.IsOpen())
  Conn.Close();

Connection string for oracle:
Data Source=TORCL;User Id=myUsername;Password=myPassword;

Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

More here


问:
Google Cloud Storage seeing incorrect content type on my static files
My google cloud storage browser is seeing the incorrect content-type on all of my static files (css, js, jpg, etc.) and this is causing a mime type error when serving these files which causes my website to not apply my css styles. Why is this happening and how can I fix this? I am linking my static files correctly and with specifying the correct content-type, but this error is still happening.

```<code><link rel="stylesheet" type="text/css" media="screen,print" href="index_files/index.css" />
<script type="text/javascript" src="index_files/index.js"></script>
</code>```

As you can see in the following images, google cloud storage is seeing these static files with content-type application/octet-stream when it should be seeing them as text/css and text/javascript.

UPDATE

The files are uploaded manually to the bucket.

答:
You will have to manually edit the content type in the console.  The instructions are in the documentation:

Open the Cloud Storage browser in the Google Cloud Console.

In the list of buckets, click on the name of the bucket that contains the desired object, and navigate to the object.

Certain pieces of object metadata, such as the object's size and storage class, are displayed along with the object's name.

Click the more actions menu () associated with the object.

Click Edit metadata.    The overlay window that appears shows the current values for the object's editable metadata.

Body:
My google cloud storage browser is seeing the incorrect content-type on all of my static files (css, js, jpg, etc.) and this is causing a mime type error when serving these files which causes my website to not apply my css styles. Why is this happening and how can I fix this? I am linking my static files correctly and with specifying the correct content-type, but this error is still happening.

<link rel="stylesheet" type="text/css" media="screen,print" href="index_files/index.css" />

As you can see in the following images, google cloud storage is seeing these static files with content-type application/octet-stream when it should be seeing them as text/css and text/javascript.

UPDATE

The files are uploaded manually to the bucket.


问:
Problem withAngular when I want to add elements in array
I have an animals array. I want to put in another array just the field "espece" of each animal.

I push all the espece of animals in especeAnimalPresenteTmp and then I remove the duplicates and save the next array in especeAnimalPresente.

I have this angular code :

```<code>import { Component, OnInit } from '@angular/core';
import { AnimalService } from "./animal.service";
import { Animal } from "./animal";

@Component({
  selector: 'app-animal',
  templateUrl: './animal.component.html',
  styleUrls: ['./animal.component.css']
})
export class AnimalComponent implements OnInit {

  private animaux:Array<Animal>;
  private especeAnimalPresente:Array<string>;
  private especeAnimalPresenteTmp:Array<string>;
  constructor(private animalService: AnimalService) { }

  ngOnInit() {
    this.recupAllAnimals();
  }

  recupAllAnimals(){
    this.animalService.getAllAnimaux().subscribe(data => {
      this.animaux = data;
      this.recupEspecePresent();
    })

  }

  recupEspecePresent(){
    // if (this.animaux){
      for (let animal of this.animaux) {
          this.especeAnimalPresenteTmp.push(animal.espece);
      }
      this.especeAnimalPresente = this.removeDuplicates(this.especeAnimalPresenteTmp);
    // }
  }

  removeDuplicates(array) {
    let unique = {};
    array.forEach(function(i) {
      if(!unique[i]) {
        unique[i] = true;
      }
    });
    return Object.keys(unique);
  }

}
</code>```

But I have this error in my console :

```<code>ERROR TypeError: "this.especeAnimalPresenteTmp is undefined"
    recupEspecePresent animal.component.ts:32
    recupAllAnimals animal.component.ts:24
    RxJS 11
    Angular 8
</code>```

Someone can help me please ?

答:
You have to initialize the array, for example in the constructor:</p>

```<code>constructor(private animalService: AnimalService) {
  this.especeAnimalPresenteTmp = [];
}
</code>```

Body:
I have an animals array. I want to put in another array just the field "espece" of each animal.

I push all the espece of animals in especeAnimalPresenteTmp and then I remove the duplicates and save the next array in especeAnimalPresente.

I have this angular code :

import { Component, OnInit } from '@angular/core';
import { AnimalService } from "./animal.service";
import { Animal } from "./animal";

@Component({
  selector: 'app-animal',
  templateUrl: './animal.component.html',
  styleUrls: ['./animal.component.css']
})
export class AnimalComponent implements OnInit {

  private animaux:Array<Animal>;
  private especeAnimalPresente:Array<string>;
  private especeAnimalPresenteTmp:Array<string>;
  constructor(private animalService: AnimalService) { }

  ngOnInit() {
    this.recupAllAnimals();
  }

  recupAllAnimals(){
    this.animalService.getAllAnimaux().subscribe(data => {
      this.animaux = data;
      this.recupEspecePresent();
    })

  }

  recupEspecePresent(){
    // if (this.animaux){
      for (let animal of this.animaux) {
          this.especeAnimalPresenteTmp.push(animal.espece);
      }
      this.especeAnimalPresente = this.removeDuplicates(this.especeAnimalPresenteTmp);
    // }
  }

  removeDuplicates(array) {
    let unique = {};
    array.forEach(function(i) {
      if(!unique[i]) {
        unique[i] = true;
      }
    });
    return Object.keys(unique);
  }

}

But I have this error in my console :

ERROR TypeError: "this.especeAnimalPresenteTmp is undefined"
    recupEspecePresent animal.component.ts:32
    recupAllAnimals animal.component.ts:24
    RxJS 11
    Angular 8

Someone can help me please ?

Body:
You have to initialize the array, for example in the constructor:

constructor(private animalService: AnimalService) {
  this.especeAnimalPresenteTmp = [];
}


问:
How do i get current processor id in macOS KEXT
I found kern/processor.h files that include current_processor().

But I cannot use current_processor() even i include kern/processor.h file.

Is there any methods to get current processor id?

Add 030420 : I need any methods that get current processor id and methods should be possible to used in KEXT.  current_processor(), cpu_number() doesn't work on KEXT.

答:
The following function is declared in <kern/cpu_number.h>:

```<code>extern int  cpu_number(void);
</code>```

and returns the index of the CPU on which the code is currently executing.

Please note that this is in the unsupported KPI however, so you need to link against com.apple.kpi.unsupported.

Also note that the result will be meaningless unless preemption is disabled, which is of course normally not the case, only when a spinlock is held, or when running in a primary interrupt handler. Preemption being enabled means that the running thread can be rescheduled at any time, so by the time your code uses the CPU number it obtained by calling the above function, it may already have been rescheduled to run on a different CPU.

Body:
The following function is declared in <kern/cpu_number.h>:

extern int  cpu_number(void);

and returns the index of the CPU on which the code is currently executing.

Please note that this is in the unsupported KPI however, so you need to link against com.apple.kpi.unsupported.

Also note that the result will be meaningless unless preemption is disabled, which is of course normally not the case, only when a spinlock is held, or when running in a primary interrupt handler. Preemption being enabled means that the running thread can be rescheduled at any time, so by the time your code uses the CPU number it obtained by calling the above function, it may already have been rescheduled to run on a different CPU.


问:
Updating CSV file in FTP server in PHP
I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution</p>

```<code><?php

// connect and login to FTP server
//ftp setup
 $ftp_server = "ftp.test.test.co.uk";
        $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
        $ftp_username='ftp_username';
        $ftp_userpass='ftp_userpass';
      $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//END database connection//

$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";

$result = $conn->query($sql);

         header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
         header("Content-Type: application/csv; ");

         // file creation
       $file = fopen('php://temp', 'W');

        $header = array("SKU","QUANTITY");
        fputcsv($file, $header);

      if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
            fputcsv($file, $row );
        }
    }

 $remote_path = "/export/AllOpenOrders.csv";

ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);

  fclose($file);
ftp_close($ftp_conn);
?>
</code>```

答:
You file handler $file points at the end of the file as you write in it. There is nothing left to write via ftp_fput.

You can reset your file pointer at the beginning of the file with rewind($file); before writing in the FTP : rewind documentation

Title: Updating CSV file in FTP server in PHP

Body:
I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution

<?php

// connect and login to FTP server
//ftp setup
 $ftp_server = "ftp.test.test.co.uk";
        $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
        $ftp_username='ftp_username';
        $ftp_userpass='ftp_userpass';
      $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//END database connection//

$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";

$result = $conn->query($sql);

         header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
         header("Content-Type: application/csv; ");

         // file creation
       $file = fopen('php://temp', 'W');

        $header = array("SKU","QUANTITY");
        fputcsv($file, $header);

      if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
            fputcsv($file, $row );
        }
    }

 $remote_path = "/export/AllOpenOrders.csv";

ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);

  fclose($file);
ftp_close($ftp_conn);
?>


问:
I have a problem in java method code which returns the division of two numbers
In this code a division method is implemented, so i want to handle 3 cases where division is undefined using try catch and throws, but it gives me an error message that the division method must return float .
package calculator3;

//Class implements interface
public class implementation  implements calc {

```<code>//Add function
    public int add(int x, int y) {
        int ans1 = x + y ;
        return ans1 ;

    }

    //Divide function
    public float divide(int x, int y) throws RuntimeException{
        try {
            if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
                throw new ArithmeticException("invalid_division");

            }
            else {
                return x / y ;
            }

        }catch  (ArithmeticException invalid_division ) {
            System.out.println("invalid_division");
        }
}
}
</code>```

答:
Your divide return type is float.

An int will never equal Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY because those are not in their range of possible values.

The function will not throw an error if it is caught.

Taking above 3 points:

```<code>//divide
public float divide(int x, int y) throws ArithmeticException{
        if (y == 0) throw new ArithmeticException("invalid_division");
        return (float)x / y; // cast x to float so a float will result
}

</code>```

Body:
In this code a division method is implemented, so i want to handle 3 cases where division is undefined using try catch and throws, but it gives me an error message that the division method must return float .
package calculator3;

//Class implements interface
public class implementation  implements calc {

//Add function
    public int add(int x, int y) {
        int ans1 = x + y ;
        return ans1 ;

    }

    //Divide function
    public float divide(int x, int y) throws RuntimeException{
        try {
            if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
                throw new ArithmeticException("invalid_division");

            }
            else {
                return x / y ;
            }

        }catch  (ArithmeticException invalid_division ) {
            System.out.println("invalid_division");
        }
}
}

Body:
Your divide return type is float.

An int will never equal Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY because those are not in their range of possible values.

The function will not throw an error if it is caught.

Taking above 3 points:

//divide
public float divide(int x, int y) throws ArithmeticException{
        if (y == 0) throw new ArithmeticException("invalid_division");
        return (float)x / y; // cast x to float so a float will result
}


问:
MySQL performance tuning for DELETE query
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

```<code>DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )
</code>```

At the same time, this query took only 4.69 seconds only to execute.

```<code>DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)
</code>```

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

答:
When deleting 40K rows, expect it to take time.  The main cost (assuming adequate indexing and a decent query) is the overhead of transactional semantics of an "atomic" delete.  This involves making a copy of each row being deleted, just in case there is a crash.  That way, InnoDB can bring the database back to what it had been before the crash.

When deleting 40% of a table, it is much faster to copy the rows to keep into another table then swap tables.

When deleting a large number of rows (regardless of the percentage), it is better to do it in chunks.  And it is best to walk through the table based on the PRIMARY KEY.

I discuss both of those techniques, plus others, in http://mysql.rjweb.org/doc.php/deletebig

As for the query formulation:

It is version-dependent; old versions of MySQL did a poor job on some flavors.

NOT IN (SELECT ...) and NOT EXISTS tend to be the worst performers.

IN (SELECT ...) and/or EXISTS may be better.

"Multi-table DELETE is another option.  It works like JOIN.

(Bottom line:  You did not say what version you are running; I can't predict which formulation will be best.)

My blog avoids the formulation debate.

Body:
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )

At the same time, this query took only 4.69 seconds only to execute.

DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.


问:
Get Selected Radio Button WITHOUT a Submit button
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

```<code>document.getElementById("results").innerHTML = NONE or A or B
</code>```

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

```

答:
Just set up click events for the buttons and populate the results area in the event callback. No JQuery or Bootstrap is required.

But, radio buttons need to have their value attribute configured so that clicking one has meaning over the others. Also, autocomplete is irrelevant with radio buttons.

// Get a reference to the result area element
let results = document.getElementById("results");

// Set up a click handler on the parent of the radio buttons so that
// any clicks to the descendants will bubble up to the parent
document.querySelector("div.btn-group").addEventListener("click", function(evt){
  // Check if a radio button triggered the event
  if(evt.target.type === "radio"){
    // Populate the results area with the value of the clicked element
    results.textContent = evt.target.value;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" value="NONE">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" value="A">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" value="B">B
  </label>
</div>

<div id="results"></div></code>```

Body:
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

document.getElementById("results").innerHTML = NONE or A or B

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

Body:
Just set up click events for the buttons and populate the results area in the event callback. No JQuery or Bootstrap is required.

But, radio buttons need to have their value attribute configured so that clicking one has meaning over the others. Also, autocomplete is irrelevant with radio buttons.

// Get a reference to the result area element
let results = document.getElementById("results");

// Set up a click handler on the parent of the radio buttons so that
// any clicks to the descendants will bubble up to the parent
document.querySelector("div.btn-group").addEventListener("click", function(evt){
  // Check if a radio button triggered the event
  if(evt.target.type === "radio"){
    // Populate the results area with the value of the clicked element
    results.textContent = evt.target.value;
  }
});

<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" value="NONE">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" value="A">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" value="B">B
  </label>
</div>

<div id="results"></div>


问:
Write extra spaces to html element with JavaScript
We have JavaScript that writes to the document title and attempts to pad it with extra spaces...

```<code>document.title = "My Title  "
</code>```

But this gets translated to "My Title  "

Anyone know how to prevent this?

答:
You can do this

```<code>const titleElement = document.getElementsByTagName('title')[0]
titleElement.innerHTML = ' '
</code>```

But as pointed out, spaces of all types are stripped.

But, if you add  (the MONGOLIAN VOWEL SEPARATOR ) to the end, it will not strip out the previous spaces.

```<code>titleElement.innerHTML = ' '
</code>```

At least in Chrome.

ContentLicense: CC BY-SA 2.5

Body:
We have JavaScript that writes to the document title and attempts to pad it with extra spaces...

document.title = "My Title  "

But this gets translated to "My Title&nbsp;&nbsp;"

Anyone know how to prevent this?

Body:
You can do this

const titleElement = document.getElementsByTagName('title')[0]
titleElement.innerHTML = '&#160;'

But as pointed out, spaces of all types are stripped.

But, if you add &#6158; (the MONGOLIAN VOWEL SEPARATOR ) to the end, it will not strip out the previous spaces.

titleElement.innerHTML = '&#6158;&#160;'

At least in Chrome.


问:
Trying to create a multithreaded program to find the total primes from 0-100000000
Hello I am trying to write a C++ multithreaded program using POSIX thread library to find the number of prime numbers between 1 and 10,000,000 (10 million) and find out how many microseconds it takes...

Creating my threads and running them works completely fine, however I feel as if there is an error found in my Prime function when determining if a number is prime or not...

I keep receiving 78496 as my output, however I desire 664579. Below is my code. Any hints or pointers would be greatly appreciated.

```<code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time;

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```
```

答:
Along with taking 10^7 as the numbers divided in thread instead of setting the limit as 10^6 ,a number of other small scale errors are there and a number of optimizations could be made -

First of all start numbers could be from 2 itself

long start_numbers[4] = {2, 2500001, 5000001, 7500001};

sum_t++ in your code may not work on edge cases. It is better to follow the following algorithm for calculating Prime function

```<code>  bool flag = false;
  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
  flag = false;

  for (long j=2; j*j <= i; j++){
      if (i % j == 0 )
      {
          flag = true;
          break;
      }
   }
   if(!flag)
        sum_t++;
  }
</code>```

After these 2 operations i am getting the result as

```<code>Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 6.62618e+06 microseconds
</code>```

edit:
( Note : in this case j is taken as long datatype but it could work as well with int in this 'example' since the tested compiler takes int as 32 bits long)

Body:
Hello I am trying to write a C++ multithreaded program using POSIX thread library to find the number of prime numbers between 1 and 10,000,000 (10 million) and find out how many microseconds it takes...

Creating my threads and running them works completely fine, however I feel as if there is an error found in my Prime function when determining if a number is prime or not...

I keep receiving 78496 as my output, however I desire 664579. Below is my code. Any hints or pointers would be greatly appreciated.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time;

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```

Body:
Along with taking 10^7 as the numbers divided in thread instead of setting the limit as 10^6 ,a number of other small scale errors are there and a number of optimizations could be made -

First of all start numbers could be from 2 itself

long start_numbers[4] = {2, 2500001, 5000001, 7500001};

sum_t++ in your code may not work on edge cases. It is better to follow the following algorithm for calculating Prime function

  bool flag = false;
  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
  flag = false;

  for (long j=2; j*j <= i; j++){
      if (i % j == 0 )
      {
          flag = true;
          break;
      }
   }
   if(!flag)
        sum_t++;
  }

After these 2 operations i am getting the result as

Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 6.62618e+06 microseconds

edit:
( Note : in this case j is taken as long datatype but it could work as well with int in this 'example' since the tested compiler takes int as 32 bits long)


问:
Post data using $.post fails with empty data
I want to send some data using jQuery

```<code>var uri = "some url";

$.post(uri,
    { message: "test"},
    {"format" : "json"},
    'html');

return false;
</code>```

When the php script gets the request the message field is empty. Why?

Edit: I use zend framework to read the post data

```<code>$this->getRequest ()->getPost ( 'message' );
</code>```

The js code from above workes on localhost but on the server message is empty. I check with isPost() which says that there is no post.

答:
You are passing two objects to $.post.  There's no reason to do this.  I think you just want this:

```<code>$.post(uri,
    { message: "test"},
    'html');
</code>```

The server will understand the format of the posted data.

Body:
I want to send some data using jQuery

var uri = "some url";

$.post(uri,
    { message: "test"},
    {"format" : "json"},
    'html');

return false;

When the php script gets the request the message field is empty. Why?

Edit: I use zend framework to read the post data

$this->getRequest ()->getPost ( 'message' );

The js code from above workes on localhost but on the server message is empty. I check with isPost() which says that there is no post.

Body:
You are passing two objects to $.post.  There's no reason to do this.  I think you just want this:

$.post(uri,
    { message: "test"},
    'html');

The server will understand the format of the posted data.


问:
How to handle UnauthorizedAccessException in asynchronous code?
Catching an UnauthorizedAccessException works fine, but it doesn't when I make the File.WriteAllBytes -> await Task.Run(() => File.WriteAllBytes(Path + vid.FullName, vid.GetBytes()));
When I do this the exception doesn't get caught. What's the best way to catch this exception, so that the MessageBox shows? Thanks.

(NOTE: This code is clearly a YouTube converter, but it is for my own personal use)

```<code> public async Task ConvertVideoAndDownloadToFolder(string link, string MP3Name = null)
        {
            try
            {
                var youtube = YouTube.Default;
                var vid = await Task.Run(() => youtube.GetVideo(link));
                await Task.Run(() => File.WriteAllBytes(Path + vid.FullName, vid.GetBytes()));
                var inputFile = new MediaFile { Filename = Path + vid.FullName };
                MediaFile outputFile;
                //Creates mp4 and mp3
                if (String.IsNullOrEmpty(MP3Name)) { outputFile = new MediaFile { Filename = $"{Path + vid.FullName}.mp3" }; }
                //only creates MP4
                else { outputFile = new MediaFile { Filename = $"{MP3Name}.mp3" }; }

                using (var engine = new Engine())
                {
                    await Task.Run(() => engine.GetMetadata(inputFile));

                    await Task.Run(() => engine.Convert(inputFile, outputFile));
                }
            }
            catch (Exception ex)
            {
                if(ex is UnauthorizedAccessException)
                {
                    MessageBox.Show($"Can't write on '{Path}' as it is protected.\rPlease choose another folder. ", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if(ex is ArgumentException)
                {
                    MessageBox.Show($"'{link}' is not a valid YouTube link, \rMake sure the video still works, or check the link for typos. ", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    throw;
                }
            }
        }
</code>```

答:
In Asynchronous programming it is very easy for exceptions to be swallowed as they typically run on another thread. This needs to be carefully managed

AggregateException stores all the exceptions that happen in different threads and therefore you do not lose any exception

```<code>
catch (AggregateException aex)
{
     foreach(var ex in aex.InnerExceptions) //This will consolidate t
     {
         Console.WriteLine(ex.Message);
     }
 }
</code>```

Reference

Body:
Catching an UnauthorizedAccessException works fine, but it doesn't when I make the File.WriteAllBytes -> await Task.Run(() => File.WriteAllBytes(Path + vid.FullName, vid.GetBytes()));
When I do this the exception doesn't get caught. What's the best way to catch this exception, so that the MessageBox shows? Thanks.

(NOTE: This code is clearly a YouTube converter, but it is for my own personal use)

 public async Task ConvertVideoAndDownloadToFolder(string link, string MP3Name = null)
        {
            try
            {
                var youtube = YouTube.Default;
                var vid = await Task.Run(() => youtube.GetVideo(link));
                await Task.Run(() => File.WriteAllBytes(Path + vid.FullName, vid.GetBytes()));
                var inputFile = new MediaFile { Filename = Path + vid.FullName };
                MediaFile outputFile;
                //Creates mp4 and mp3
                if (String.IsNullOrEmpty(MP3Name)) { outputFile = new MediaFile { Filename = $"{Path + vid.FullName}.mp3" }; }
                //only creates MP4
                else { outputFile = new MediaFile { Filename = $"{MP3Name}.mp3" }; }

                using (var engine = new Engine())
                {
                    await Task.Run(() => engine.GetMetadata(inputFile));

                    await Task.Run(() => engine.Convert(inputFile, outputFile));
                }
            }
            catch (Exception ex)
            {
                if(ex is UnauthorizedAccessException)
                {
                    MessageBox.Show($"Can't write on '{Path}' as it is protected.\rPlease choose another folder. ", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if(ex is ArgumentException)
                {
                    MessageBox.Show($"'{link}' is not a valid YouTube link, \rMake sure the video still works, or check the link for typos. ", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    throw;
                }
            }
        }

Body:
In Asynchronous programming it is very easy for exceptions to be swallowed as they typically run on another thread. This needs to be carefully managed

AggregateException stores all the exceptions that happen in different threads and therefore you do not lose any exception

catch (AggregateException aex)
{
     foreach(var ex in aex.InnerExceptions) //This will consolidate t
     {
         Console.WriteLine(ex.Message);
     }
 }

Reference


问:
How to access frames of RTCVideoRenderer ? (ios)
I try to access frames of RTCVideoRenderer without success, can you help me please ?

I noticed that there is a "didCaptureVideoFrame" method in RTCVideoCapturerDelegate, but not in RTCVideoViewDelegate.
I have never done objc, I added a method in RTCVideoViewDelegate to get frames (bellow "didChangeVideoSize"), but it do not get fired, I guess it do not work like that.

I am able to access frames from the remote using Android using the "onFrame" of VideoSink, I thought it would be that easy using ios.

PS: To add the method, I took the framework from the pod and put it in the project, because I noticed that when you modify a pod, changes do not apply.
Here is the line I added :

```<code>- (void)videoView:(id<RTCVideoRenderer>)videoView didRenderVideoFrame:(RTCVideoFrame *)frame;
</code>```

I will now try to compile the library with the changes I want.

EDIT:

I am now compiling the library, I noticed the need to change several files to be able to access frames, it will not be done just by adding 10 lines.

答:
Solved thanks to this : How to get frame data in AppRTC iOS app for video modifications?

I used this line instead (because names changed since) :

```<code>@property(atomic, strong) RTCVideoFrame* videoFrame;
</code>```

I wanted a "onFrame" like VideoSink on Android, but it will be ok for now.

Body:
I try to access frames of RTCVideoRenderer without success, can you help me please ?

I noticed that there is a "didCaptureVideoFrame" method in RTCVideoCapturerDelegate, but not in RTCVideoViewDelegate.
I have never done objc, I added a method in RTCVideoViewDelegate to get frames (bellow "didChangeVideoSize"), but it do not get fired, I guess it do not work like that.

I am able to access frames from the remote using Android using the "onFrame" of VideoSink, I thought it would be that easy using ios.

PS: To add the method, I took the framework from the pod and put it in the project, because I noticed that when you modify a pod, changes do not apply.
Here is the line I added :

- (void)videoView:(id<RTCVideoRenderer>)videoView didRenderVideoFrame:(RTCVideoFrame *)frame;

I will now try to compile the library with the changes I want.

EDIT:

I am now compiling the library, I noticed the need to change several files to be able to access frames, it will not be done just by adding 10 lines.

Body:
Solved thanks to this : How to get frame data in AppRTC iOS app for video modifications?

I used this line instead (because names changed since) :

@property(atomic, strong) RTCVideoFrame* videoFrame;

I wanted a "onFrame" like VideoSink on Android, but it will be ok for now.


答:
You referenced by id="display", but it was set to class="display".

async function fetchData() {
  const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
  const data = await response.json();

  document.getElementById("display").innerHTML = data["articles"].map(
    article => `

${article.title}

${article.description}

${article.author}

${article.url} target="_blank">

`).join('');
}

fetchData();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="display"></div></code>```

Title: how do I convert json data into Html tag?

Body:
I am trying to display JSON data in the Html tag. But I got the error:

Uncaught (in promise) TypeError.

async function fetchData() {
        const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
        const data = await response.json();
        console.log(data);

        document.getElementById("display").insertAdjacentText = `
        ${data.articles.map(function (article) {
            return `

${article.title}

${article.description}

${article.author}

${article.url} target="_blank">

             `
        }).join('')}`

    }
    fetchData();

Body:
You referenced by id="display", but it was set to class="display".

async function fetchData() {
  const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
  const data = await response.json();

  document.getElementById("display").innerHTML = data["articles"].map(
    article => `<ul id="news-articles">
            <li class="article"><img class="article-img" src="${article.urlToImage}" alt="article-img"></li>
            <li class="article"><h2 class="article-title">${article.title}</h2></li>
            <li class="article"><p class="article-description">${article.description}</p></li>
           <li class="article"><span class="article-author">${article.author}</span></li>
            <li class="article"><a class="article-link" href="">${article.url} target="_blank"> </a></li></ul>`).join('');
}

fetchData();

<div id="display"></div>


问:
Android studio 3.5 for Mac OSX Catalina is crashing on the index process
When I open my project, in the index process the application is quitting and show me this error, I tried:

Invalidating and restarting,

Removing the Iml file

Adding this configuration to VMOptions file:

-Dsun.font.layoutengine=icu

Reseting the project and downloading it again

Formatting the computer

Changing my branch

Erasing Gradle cache file

But they didn't work.

答: Kindly Update your mac OS to 10.15.3 which is latest for now and update your android studio and emulator updates.</p>


问:
How to add a notification to a Quasar project inside of a Typescript store
I'm trying to use Quasar's notification library inside of a Typescript store within one of my components using "this.$q.notify({}) but I don't have access to it inside of the store. I would like to know what the right way would be to go about doing this. This line of code is being called in the deleteCourse Action.

Store code:

```<code>import { Module, VuexModule, getModule, Mutation, Action } from 'vuex-module-decorators'
import { websocket } from 'src/boot/socket.io-client'
import store from 'src/store'
import { DataTablePagination } from '../types'
import { Course } from './types'
import { LayoutModule } from 'src/store/layout/index'

export { Course } from './types'
export { DataTablePagination } from '../types'

export interface CourseState {
  pagination: DataTablePagination
  courses: Course []
  filter: string,
  disabled: boolean,
  selected: Course [],
  active: boolean
}

@Module({
  name: 'course',
  namespaced: true,
  dynamic: true,
  store
})

class CourseClass extends VuexModule implements CourseState {
  public pagination: DataTablePagination = {
    descending: false,
    rowsNumber: 0,
    rowsPerPage: 10,
    page: 1,
    sortBy: 'name'
  }
  public courses : Course [] = []
  public filter: string = ''
  public disabled: boolean = true
  public selected: Course [] = []
  public active: boolean = true

  @Mutation
  SET_ACTIVE(active: boolean) {
    this.active=active
  }

  @Mutation
  SET_PAGINATION(pagination: DataTablePagination) {
    this.pagination=pagination
  }

  @Mutation
  SET_SELECTED(selected: Course []) {
    this.selected=selected
  }

  @Mutation
  SET_FILTER(filter: string) {
    this.filter=filter
  }

  @Mutation
  SET_COURSES(courses: Course []) {
    this.courses=courses
  }

  @Mutation
  SET_DISABLED(disabled: boolean) {
    this.disabled=disabled
  }

  @Action
  public async addCourse(input: Course) {
    websocket.emit('query', `mutation {
      createCourse (
        course: {
          code: "${input.code}"
          name: "${input.name}"
          creditHours: ${input.creditHours}
          numberOfLabs: ${input.numberOfLabs}
          contactHours: ${input.contactHours}
          chargeableCredits: 0
        }
      ) {
        ok
        message
      }
  }`, (response: {
    errors: any
    data: {
      createAcademicProgram: {
        ok: boolean
        message: String
      }
    }
  }) => {
      this.fetchCourses()
      if(response.data) {
        this.fetchCourses()
      }
      else {
        LayoutModule.SET_ERRORMSGOPENED(true)
        LayoutModule.SET_MESSAGE('Addition Failed')
      }
    })
  }

  @Action
  public async deleteCourse(input: Course) {
    websocket.emit('query', `mutation {
      deleteCourse (
        courseId: "${input.id}"
      )  {
        id
        ok
        message
      }
    }`, (response: {
      errors: any;
      data: {
        deleteCourse: {
          id: any;
          ok: boolean;
          message: String
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        this.$q.notify({
          message: 'Course Deleted Successfully'
        })
        //this.SET_SELECTED([])
      }
      else {
        LayoutModule.SET_MESSAGE("Deletion Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }

  @Action
  public async editCourse(input: Course) {
    websocket.emit('query', `mutation {
      updateCourse (
        course: {
          id: "${input.id}"
          code: "${input.code}"
          name: "${input.name}"
          creditHours: ${input.creditHours}
          numberOfLabs: ${input.numberOfLabs}
          contactHours: ${input.contactHours}
          chargeableCredits: 0
        }
      ) {
        id
        ok
        message
      }
    }`, (response: {
      errors: any
      data: {
        updateCourse: {
          id: string
          ok: boolean
          message: string
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        this.SET_SELECTED([input])
      }
      else {
        LayoutModule.SET_MESSAGE("Update Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }

  @Action
  public async fetchCourses() {
    const order = this.pagination.sortBy !== null ? `order: {
      by: ${this.pagination.sortBy}
      dir: ${this.pagination.descending ? 'DESC' : 'ASC'}
    }` : ''
    websocket.emit('query', `{
      courses(
        page: {
          skip: ${(this.pagination.page - 1) * this.pagination.rowsPerPage},
          first: ${this.pagination.rowsPerPage}
        }
        filter: {
          ilike: {
            name: "${this.filter}"
          }
        }
        ${order}
      ) {
        pagination {
          total
          listTotal
        }
        list {
          id
          code
          name
          creditHours
          numberOfLabs
          contactHours
        }
      }
    }`, (response: {
      errors: any
      data: {
        courses: {
          list: Course[]
          pagination: {
            total: number
            listTotal: number
          }
        }
      }
    }) => {
      this.SET_COURSES(response.data.courses.list)
      this.pagination.rowsNumber = response.data.courses.pagination.total
    })
  }
}

export const CourseModule = getModule(CourseClass)
</code>```

答:
Was able to solve this by importing 'Notify' from Quasar and using the create function.</p>

```<code>import { Notify } from 'quasar'

@Action
  public async deleteCourse(input: Course) {
    websocket.emit('query', `mutation {
      deleteCourse (
        courseId: "${input.id}"
      )  {
        id
        ok
        message
      }
    }`, (response: {
      errors: any;
      data: {
        deleteCourse: {
          id: any;
          ok: boolean;
          message: String
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        Notify.create({
          timeout: 2000,
          position: 'center',
          color: 'primary',
          message: 'Course Deleted Successfully'
        })
      }
      else {
        LayoutModule.SET_MESSAGE("Deletion Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }
</code>```

Body:
I'm trying to use Quasar's notification library inside of a Typescript store within one of my components using "this.$q.notify({}) but I don't have access to it inside of the store. I would like to know what the right way would be to go about doing this. This line of code is being called in the deleteCourse Action.

Store code:

import { Module, VuexModule, getModule, Mutation, Action } from 'vuex-module-decorators'
import { websocket } from 'src/boot/socket.io-client'
import store from 'src/store'
import { DataTablePagination } from '../types'
import { Course } from './types'
import { LayoutModule } from 'src/store/layout/index'

export { Course } from './types'
export { DataTablePagination } from '../types'

export interface CourseState {
  pagination: DataTablePagination
  courses: Course []
  filter: string,
  disabled: boolean,
  selected: Course [],
  active: boolean
}

@Module({
  name: 'course',
  namespaced: true,
  dynamic: true,
  store
})

class CourseClass extends VuexModule implements CourseState {
  public pagination: DataTablePagination = {
    descending: false,
    rowsNumber: 0,
    rowsPerPage: 10,
    page: 1,
    sortBy: 'name'
  }
  public courses : Course [] = []
  public filter: string = ''
  public disabled: boolean = true
  public selected: Course [] = []
  public active: boolean = true

  @Mutation
  SET_ACTIVE(active: boolean) {
    this.active=active
  }

  @Mutation
  SET_PAGINATION(pagination: DataTablePagination) {
    this.pagination=pagination
  }

  @Mutation
  SET_SELECTED(selected: Course []) {
    this.selected=selected
  }

  @Mutation
  SET_FILTER(filter: string) {
    this.filter=filter
  }

  @Mutation
  SET_COURSES(courses: Course []) {
    this.courses=courses
  }

  @Mutation
  SET_DISABLED(disabled: boolean) {
    this.disabled=disabled
  }

  @Action
  public async addCourse(input: Course) {
    websocket.emit('query', `mutation {
      createCourse (
        course: {
          code: "${input.code}"
          name: "${input.name}"
          creditHours: ${input.creditHours}
          numberOfLabs: ${input.numberOfLabs}
          contactHours: ${input.contactHours}
          chargeableCredits: 0
        }
      ) {
        ok
        message
      }
  }`, (response: {
    errors: any
    data: {
      createAcademicProgram: {
        ok: boolean
        message: String
      }
    }
  }) => {
      this.fetchCourses()
      if(response.data) {
        this.fetchCourses()
      }
      else {
        LayoutModule.SET_ERRORMSGOPENED(true)
        LayoutModule.SET_MESSAGE('Addition Failed')
      }
    })
  }

  @Action
  public async deleteCourse(input: Course) {
    websocket.emit('query', `mutation {
      deleteCourse (
        courseId: "${input.id}"
      )  {
        id
        ok
        message
      }
    }`, (response: {
      errors: any;
      data: {
        deleteCourse: {
          id: any;
          ok: boolean;
          message: String
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        this.$q.notify({
          message: 'Course Deleted Successfully'
        })
        //this.SET_SELECTED([])
      }
      else {
        LayoutModule.SET_MESSAGE("Deletion Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }

  @Action
  public async editCourse(input: Course) {
    websocket.emit('query', `mutation {
      updateCourse (
        course: {
          id: "${input.id}"
          code: "${input.code}"
          name: "${input.name}"
          creditHours: ${input.creditHours}
          numberOfLabs: ${input.numberOfLabs}
          contactHours: ${input.contactHours}
          chargeableCredits: 0
        }
      ) {
        id
        ok
        message
      }
    }`, (response: {
      errors: any
      data: {
        updateCourse: {
          id: string
          ok: boolean
          message: string
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        this.SET_SELECTED([input])
      }
      else {
        LayoutModule.SET_MESSAGE("Update Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }

  @Action
  public async fetchCourses() {
    const order = this.pagination.sortBy !== null ? `order: {
      by: ${this.pagination.sortBy}
      dir: ${this.pagination.descending ? 'DESC' : 'ASC'}
    }` : ''
    websocket.emit('query', `{
      courses(
        page: {
          skip: ${(this.pagination.page - 1) * this.pagination.rowsPerPage},
          first: ${this.pagination.rowsPerPage}
        }
        filter: {
          ilike: {
            name: "${this.filter}"
          }
        }
        ${order}
      ) {
        pagination {
          total
          listTotal
        }
        list {
          id
          code
          name
          creditHours
          numberOfLabs
          contactHours
        }
      }
    }`, (response: {
      errors: any
      data: {
        courses: {
          list: Course[]
          pagination: {
            total: number
            listTotal: number
          }
        }
      }
    }) => {
      this.SET_COURSES(response.data.courses.list)
      this.pagination.rowsNumber = response.data.courses.pagination.total
    })
  }
}

export const CourseModule = getModule(CourseClass)

Body:
Was able to solve this by importing 'Notify' from Quasar and using the create function.

import { Notify } from 'quasar'

@Action
  public async deleteCourse(input: Course) {
    websocket.emit('query', `mutation {
      deleteCourse (
        courseId: "${input.id}"
      )  {
        id
        ok
        message
      }
    }`, (response: {
      errors: any;
      data: {
        deleteCourse: {
          id: any;
          ok: boolean;
          message: String
        }
      }
    }) => {
      if(response.data) {
        this.fetchCourses()
        Notify.create({
          timeout: 2000,
          position: 'center',
          color: 'primary',
          message: 'Course Deleted Successfully'
        })
      }
      else {
        LayoutModule.SET_MESSAGE("Deletion Failed")
        LayoutModule.SET_ERRORMSGOPENED(true)
      }
    })
  }