问:
nodemon sometimes not working on my node.js app
I'm using nodemon on my node.js app to restart the server on its own for any change made.

I just made some changes on one of the route file and it gave me 404 error so I thought something must went wrong with my code but when I opened it on a new browser window or restarted Terminal, it worked fine with the changed code.

Has anyone experienced this with nodemon and perhaps can share a solution?

答:
nodemon by default watches only few of the extension i.e only in some of the file you make changes it gets restarted. If you are using any other extension in your file you can always try
nodemon app.js -e js,hbs

assuming -
 app.js is your main file name
-e: stands for extension
js and hbs are file extension like app.js/header.hbs


来源: stackexchange

问:
Spring-Boot: Dependency Injection depending on the configuration (and using interfaces)
I have the following question regarding the structure of my application architecture.
Assume my application consists of the following components

First of all a @ConfigurationProperties, which initializes my needed properties (here only a type to select a provider).
In addition, a bean of the type "Provider" is to be registered at this point depending on the specified type. This type is implemented as an interface and has two concrete implementations in this example (ProviderImplA & ProviderImplB).

@Configuration
@Profile("provider")
@ConfigurationProperties(prefix = "provider")
@ConditionalOnProperty(prefix = "provider", name = ["type"])
class ProviderConfiguration {
    lateinit var type: String

    @Bean(name = ["provider"])
    fun provider(): Provider {
        return when (type) {
            "providerA" -> ProviderImplA()
            "providerB" -> ProviderImplB()
        }

    }

}
```
<p>Next, only the two concrete implementation of the interface.</p>
<pre class="lang-kotlin prettyprint-override"><code>class ProviderImplA: Provider {

    @Autowired
    lateinit var serviceA: ServiceA

}
</code>```

class ProviderImplB: Provider {

    @Autowired
    lateinit var serviceA: ServiceA
    @Autowired
    lateinit var serviceB: ServiceB
    @Autowired
    lateinit var serviceC: ServiceC

}
```
<p>And last but not least the interface itself.</p>
<pre class="lang-kotlin prettyprint-override"><code>interface Provider{
    fun doSomething()
}
</code>```

Now to the actual problem or better my question:

Because my concrete implementations (ProviderImplA and ProviderImplB) are no valid defined beans (missing annotation e.g. @Component), but they have to use their own @Service components, it is not possible to use @Autworie at this point. I would like to avoid different profiles/configurations if possible, therefore the initialization by property. How can I still use the individual @Service's within my implementations and still create the provider beans manually, depending on the configuration (only one provider exists at runtime)? Maybe you have other suggestions or improvements?

答:
When instantiating objects directly, spring cannot control its life cycle, so you must create an @Bean for each 'Provider'

```<code>@Bean(name = ["providerA"])
@Lazy
fun providerA(): Provider {
  return ProviderImplA()
}

@Bean(name = ["providerB"])
@Lazy
fun providerB(): Provider {
   return ProviderImplB()
}
</code>```

IdentityProviderConfiguration class

```<code>IdentityProviderConfiguration {
  var context: ApplicationContext
  ...

  fun provider(): Provider {
    return when (type) {
     "providerA" -> context.getBean("providerA")
     "providerB" -> context.getBean("providerB")
    }
  }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following question regarding the structure of my application architecture.
Assume my application consists of the following components

First of all a @ConfigurationProperties, which initializes my needed properties (here only a type to select a provider).
In addition, a bean of the type "Provider" is to be registered at this point depending on the specified type. This type is implemented as an interface and has two concrete implementations in this example (ProviderImplA & ProviderImplB).

@Configuration
@Profile("provider")
@ConfigurationProperties(prefix = "provider")
@ConditionalOnProperty(prefix = "provider", name = ["type"])
class ProviderConfiguration {
    lateinit var type: String

    @Bean(name = ["provider"])
    fun provider(): Provider {
        return when (type) {
            "providerA" -> ProviderImplA()
            "providerB" -> ProviderImplB()
        }

    }

}

Next, only the two concrete implementation of the interface.

class ProviderImplA: Provider {

    @Autowired
    lateinit var serviceA: ServiceA

}

class ProviderImplB: Provider {

    @Autowired
    lateinit var serviceA: ServiceA
    @Autowired
    lateinit var serviceB: ServiceB
    @Autowired
    lateinit var serviceC: ServiceC

}

And last but not least the interface itself.

interface Provider{
    fun doSomething()
}

Now to the actual problem or better my question:

Because my concrete implementations (ProviderImplA and ProviderImplB) are no valid defined beans (missing annotation e.g. @Component), but they have to use their own @Service components, it is not possible to use @Autworie at this point. I would like to avoid different profiles/configurations if possible, therefore the initialization by property. How can I still use the individual @Service's within my implementations and still create the provider beans manually, depending on the configuration (only one provider exists at runtime)? Maybe you have other suggestions or improvements?

Body:
When instantiating objects directly, spring cannot control its life cycle, so you must create an @Bean for each 'Provider'

@Bean(name = ["providerA"])
@Lazy
fun providerA(): Provider {
  return ProviderImplA()
}

@Bean(name = ["providerB"])
@Lazy
fun providerB(): Provider {
   return ProviderImplB()
}

IdentityProviderConfiguration class

IdentityProviderConfiguration {
  var context: ApplicationContext
  ...

  fun provider(): Provider {
    return when (type) {
     "providerA" -> context.getBean("providerA")
     "providerB" -> context.getBean("providerB")
    }
  }

}


问:
SQLite: Maximum amount across the column and return column name
I am struggling getting column name for max test score across the columns.

I have managed to get max_score

```<code>select *, max(Test_1, Test_2, Test_3) as max_score
from result_table;
</code>```

But what I need is a column name. I have many columns to compare so I want to avoid using

```<code> case when (Test_1 > Test_2) and (Test_1 > Test_3) then 'Test_1'
</code>```

My desired outcome is in yellow.

答:
You don't need to check all the pairs of the columns.

Use the CASE expression like this:

```<code>select *,
  case max(Test_1, Test_2, Test_3)
    when Test_1 then 'Test_1'
    when Test_2 then 'Test_2'
    when Test_3 then 'Test_3'
  end as max_score
from result_table;
</code>```

or:

```<code>select *,
  'Test_' ||
  case max(Test_1, Test_2, Test_3)
    when Test_1 then 1
    when Test_2 then 2
    when Test_3 then 3
  end as max_score
from result_table;
</code>```

Body:
I am struggling getting column name for max test score across the columns.

I have managed to get max_score

select *, max(Test_1, Test_2, Test_3) as max_score
from result_table;

But what I need is a column name. I have many columns to compare so I want to avoid using

 case when (Test_1 > Test_2) and (Test_1 > Test_3) then 'Test_1'

My desired outcome is in yellow.

Body:
You don't need to check all the pairs of the columns.

Use the CASE expression like this:

select *,
  case max(Test_1, Test_2, Test_3)
    when Test_1 then 'Test_1'
    when Test_2 then 'Test_2'
    when Test_3 then 'Test_3'
  end as max_score
from result_table;

or:

select *,
  'Test_' ||
  case max(Test_1, Test_2, Test_3)
    when Test_1 then 1
    when Test_2 then 2
    when Test_3 then 3
  end as max_score
from result_table;


问:
How to use coalesce with select in gremlin?
Query

```<code>g.V().
has('id', 1).
out('follows').
as('x').
out('knows').
as('y').
project('Name').
by(select('x').by('name'))
</code>```

Here I want to use coalesce in the projection because there are vertices where name property does not exist.

I tried this but it doesn't work,

```<code>by(coalesce(select('x').by('name'), constant('null'))
</code>```

答:
Change the by to values and it should work:

```<code>g.V().
  has('id', 1).
  out('follows').
  as('x').
  out('knows').
  as('y').
  project('Name').
    by(coalesce(select('x').values('name'), constant('null')))
</code>```

Body:
Query

g.V().
has('id', 1).
out('follows').
as('x').
out('knows').
as('y').
project('Name').
by(select('x').by('name'))

Here I want to use coalesce in the projection because there are vertices where name property does not exist.

I tried this but it doesn't work,

by(coalesce(select('x').by('name'), constant('null'))

Body:
Change the by to values and it should work:

g.V().
  has('id', 1).
  out('follows').
  as('x').
  out('knows').
  as('y').
  project('Name').
    by(coalesce(select('x').values('name'), constant('null')))


问:
running the application on controller
I'm still a beginner with spring boot, I'm using spring JPA to fetch the data from multiple tables in the same database and everything going fine, I used to run my application at the Main but here I have added a Controller class and running things there, then i used @Scheduled(fixedRate=7000) instead of creating an infinite loop to keep check the data from db and stay live, the application working fine but as far as at the running time application executed twice  instead of once at the beginning before scheduling, a is there any idea about what happened here :

Mainclass :

```<code>@SpringBootApplication
@EnableScheduling
public class AccessingDataJpaApplication {
    public static void main(String[] args) throws Exception{
        SpringApplication.run(AccessingDataJpaApplication.class);
    }
}
</code>```

Controller class :

```<code>@Controller
@EnableScheduling
public class MainController {

    private static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private MessageRepository messageRepository;

    private Set<String> camps = new HashSet<String>();

    @Bean
    @Scheduled(fixedRate=7000)
    public void run(){
        logger.info("Running");
        if((customerRepository.findAllByStatusAndCampType(0, 1).size()) > 0 ){
            for(Customer customer : customerRepository.findAll()){
                System.out.println(customer.getCampCd());
                camps.add(customer.getCampCd());
                }
            System.out.println("----------------------------------------");
            for(MessageCampain messagecampain : messageRepository.findAllByCampCdIn(camps)) {
                System.out.println(messagecampain.toString());
                }
            System.out.println("------------------------------------------");
            for(String value : camps) {
                System.out.println(value);
                }
            }
        }
}
</code>```

execution log :

```<code>[           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
[           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
[           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[           main] c.e.accessingdatajpa.MainController      : Running
[           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
[           main] c.e.a.AccessingDataJpaApplication        : Started AccessingDataJpaApplication in 5.467 seconds (JVM running for 6.242)
[   scheduling-1] c.e.accessingdatajpa.MainController      : Running
[   scheduling-1] c.e.accessingdatajpa.MainController      : Running
</code>```

you can notice that at Running word

答:
It is because you annotate the run() in MainController as @Bean , which will creates a lite mode bean called run. (Spring represents this bean as the type of NullBean internally)

So , the 1st call of 'Running' in the main thread is due to spring instantiate this run bean. The remaining calls of 'Running' in the scheduling-1 thread are due to the the effect of @Scheduled. So please remove @Bean from the run() as it does not have any points to create a null bean ...

@Scheduled(fixedRate=7000)
public void run(){

}
```

Title: running the application on controller

Body:
I'm still a beginner with spring boot, I'm using spring JPA to fetch the data from multiple tables in the same database and everything going fine, I used to run my application at the Main but here I have added a Controller class and running things there, then i used @Scheduled(fixedRate=7000) instead of creating an infinite loop to keep check the data from db and stay live, the application working fine but as far as at the running time application executed twice  instead of once at the beginning before scheduling, a is there any idea about what happened here :

Mainclass :

@SpringBootApplication
@EnableScheduling
public class AccessingDataJpaApplication {
    public static void main(String[] args) throws Exception{
        SpringApplication.run(AccessingDataJpaApplication.class);
    }
}

Controller class :

@Controller
@EnableScheduling
public class MainController {

    private static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private MessageRepository messageRepository;

    private Set<String> camps = new HashSet<String>();

    @Bean
    @Scheduled(fixedRate=7000)
    public void run(){
        logger.info("Running");
        if((customerRepository.findAllByStatusAndCampType(0, 1).size()) > 0 ){
            for(Customer customer : customerRepository.findAll()){
                System.out.println(customer.getCampCd());
                camps.add(customer.getCampCd());
                }
            System.out.println("----------------------------------------");
            for(MessageCampain messagecampain : messageRepository.findAllByCampCdIn(camps)) {
                System.out.println(messagecampain.toString());
                }
            System.out.println("------------------------------------------");
            for(String value : camps) {
                System.out.println(value);
                }
            }
        }
}

execution log :

[           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
[           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
[           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[           main] c.e.accessingdatajpa.MainController      : Running
[           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
[           main] c.e.a.AccessingDataJpaApplication        : Started AccessingDataJpaApplication in 5.467 seconds (JVM running for 6.242)
[   scheduling-1] c.e.accessingdatajpa.MainController      : Running
[   scheduling-1] c.e.accessingdatajpa.MainController      : Running

you can notice that at Running word


问:
Print list in terminal on multiple lines
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

```<code>list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')
</code>```

Output:

```<code>3 5 6 9 10 12 15 18 20 21 24 25 etc...
</code>```

But i want this one:

```<code>3 5 6 9 10
12 15 18 20 21
</code>```

答: You could add an if statement before you print, to determine whether you want to have end be a blank or a newline character.

Body:
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')

Output:

3 5 6 9 10 12 15 18 20 21 24 25 etc...

But i want this one:

3 5 6 9 10
12 15 18 20 21


问:
Saving an Arraycollection field to mysql/php using actionscript
How do you save an arraycollection field in an object to a mysql database. I usually would have used a for each item in array collection field then pass a unique key to it so it track it back later, but thats getting cumbersome now.
Is there a way to save an arraycollection that also allows easy update of the arraycollection item.

Thanks in advance

Johnny

答: If you woun't update some elements of collection separately, you may store it in one row (values of array separated with ',' in one string). Use blob fields if the string will be long. If you need to update some part in that collection you may tre to derive out that part in separate row. But it's not good practice, so if you want to update something putting each element of collection in a separate field is probably the best solution.</p>

ContentLicense: CC BY-SA 3.0


问:
Is there any reason to use enum params over bit flags in c#?
Lets say, for example, I have two implementations, one with bit flags and one with simple enum:

1) bit flags

```<code>[Flags]
public enum LettersBitFlags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}
</code>```

```<code>public static bool IsLetterBBitFlags(LettersBitFlags letters)
{
    return (letters & LettersBitFlags.B) != 0;
}

</code>```

2) simple enum

```<code>public enum Letters
{
    A,
    B,
    C,
    D
}
</code>```

```<code>public static bool IsLetterBParams(params Letters[] letters)
{
    return letters.Any(x => x == Letters.B);
}
</code>```

They obviously can be used like this:

```<code>Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.A | LettersBitFlags.D)); //false
Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.B | LettersBitFlags.C)); //true

Console.WriteLine(IsLetterBParams(Letters.A, Letters.D)); //false
Console.WriteLine(IsLetterBParams(Letters.B, Letters.C)); //true
</code>```

Is there any practical reason to choose one over the other? As I see, they give the same result, but maybe some performance or anything else should make me use one and did not use the other?

答:
They have different meanings. Flags are characterised by the fact that it's meaningful to OR them together; enums are simply discrete lumps of data, and the fact that they are numerical under the covers is nothing more than an implementation detail.

If you use flags where it's not meaningful to OR two of them together, you will badly mislead anyone who comes to use your data type. Conversely, if you use an enum where you meant a flag, then you'll have to manually capture and name exponentially many enum cases.

Body:
Lets say, for example, I have two implementations, one with bit flags and one with simple enum:

1) bit flags

[Flags]
public enum LettersBitFlags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}

public static bool IsLetterBBitFlags(LettersBitFlags letters)
{
    return (letters & LettersBitFlags.B) != 0;
}

2) simple enum

public enum Letters
{
    A,
    B,
    C,
    D
}

public static bool IsLetterBParams(params Letters[] letters)
{
    return letters.Any(x => x == Letters.B);
}

They obviously can be used like this:

Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.A | LettersBitFlags.D)); //false
Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.B | LettersBitFlags.C)); //true

Console.WriteLine(IsLetterBParams(Letters.A, Letters.D)); //false
Console.WriteLine(IsLetterBParams(Letters.B, Letters.C)); //true

Is there any practical reason to choose one over the other? As I see, they give the same result, but maybe some performance or anything else should make me use one and did not use the other?


问:
How to pass data from HTML page to PHP script without reloading the page?
Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.

Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.

Note: I don't want to reload my page.

HTML Code:

```<code><div id="section" style="display: none;">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
        numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
        commodi voluptatum!
    </p>
</div>
<div id="myForm">
    <form id="testForm" method="post" action="#">
        <input id="form_name" type="text" name="name" class="form-control">
        <input type="submit" name="submit" class="btn btn-send" value="submit">
    </form>
</div>
</code>```

JavaScript Code:

```<code>const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    // Please suggest the flow and code for call PHP script from here

    form.style.display = 'none';
    sectionDiv.style.display = 'block';
});
</code>```

Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..

PHP Code:

```<code>include("db.php");

if (isset($_POST['submit']))
{
    $form_name=  $_POST['name'];
    $query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
    if(mysqli_query($conn, $query))
    {
        echo "asdfghjkl";
    }
    else
    {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
    }
}
</code>```

Thanks for your help in advance..

答:
You are using pure javascript. You can send post request to server by using XMLHttpRequest.

```<code>form.addEventListener('submit', function (e) {
    e.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/your-request-path', true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() { // Call a function when the state changes.
      if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
         form.style.display = 'none';
         sectionDiv.style.display = 'block';
      }
    }
    xhr.send("your form data");

});
</code>```

For reference xmlhttprequest you may visit https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send this url.

Body:
Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.

Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.

Note: I don't want to reload my page.

HTML Code:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
        numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
        commodi voluptatum!

    <form id="testForm" method="post" action="#">
        <input id="form_name" type="text" name="name" class="form-control">
        <input type="submit" name="submit" class="btn btn-send" value="submit">
    </form>

JavaScript Code:

const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    // Please suggest the flow and code for call PHP script from here

    form.style.display = 'none';
    sectionDiv.style.display = 'block';
});

Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..

PHP Code:

include("db.php");

if (isset($_POST['submit']))
{
    $form_name=  $_POST['name'];
    $query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
    if(mysqli_query($conn, $query))
    {
        echo "asdfghjkl";
    }
    else
    {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
    }
}

Thanks for your help in advance..

Body:
You are using pure javascript. You can send post request to server by using XMLHttpRequest.

form.addEventListener('submit', function (e) {
    e.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/your-request-path', true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() { // Call a function when the state changes.
      if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
         form.style.display = 'none';
         sectionDiv.style.display = 'block';
      }
    }
    xhr.send("your form data");

});

For reference xmlhttprequest you may visit https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send this url.


问:
Background not changing color
So I'm trying to change the background on a full screen game I'm making from a tutorial, I'm trying to change the background to green, but it stays black, what's wrong with the code?

Screen.java

```<code>package debels;

import java.awt.*;
import javax.swing.JFrame;

public class Screen {
    private GraphicsDevice vc;

    public Screen(){
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        vc = env.getDefaultScreenDevice();
    }

    public void setFullScreen(DisplayMode dm, JFrame window){
        window.setUndecorated(true);
        window.setResizable(false);
        vc.setFullScreenWindow(window);

        if (dm != null && vc.isDisplayChangeSupported()){
            try{
                vc.setDisplayMode(dm);
            }catch (Exception e){}
        }
    }

    public Window getFullScreen(){
        return vc.getFullScreenWindow();
    }

    public void restoreScreen(){
        Window w = vc.getFullScreenWindow();
        if (w != null){
            w.dispose();
        }
        vc.setFullScreenWindow(null);
    }
}
</code>```

Main.java

```<code>package debels;

import java.awt.*;
import javax.swing.*;

public class Main extends JFrame{
    private static final long serialVersionUID = -7498470134154894036L;

    public static void main(String[] args){
        DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
        Main m = new Main();
        m.run(dm);
    }

    public void run(DisplayMode dm){
        setBackground(Color.GREEN);
        setForeground(Color.BLUE);
        setFont(new Font("Arial", Font.PLAIN, 24));

        Screen s = new Screen();
        try{
            s.setFullScreen(dm, this);
            try{
                Thread.sleep(5000);
            }catch(Exception e){}
        }finally{
            s.restoreScreen();
        }
    }

    public void paint(Graphics g){
        g.drawString("Hello",  200, 200);
    }
}
</code>```

答:
You just need to make 3 little changes and it will work. Follow these steps:

Step-1:Add getContentPane() to setBackgroud() which is present in the run() method

```<code>getContentPane().setBackground(Color.GREEN);
</code>```

Step-2: Cut & paste below lines from run() method to paint() method.

```<code>getContentPane().setBackground(Color.GREEN);
setForeground(Color.BLUE);
setFont(new Font("Arial", Font.PLAIN, 24));
</code>```

step-3: Add super.paint(g) in the starting of paint() method. the whole paint() method will look like this;

```<code>public void paint(Graphics g){
        super.paint(g);
        getContentPane().setBackground(Color.GREEN);
        setForeground(Color.BLUE);
        setFont(new Font("Arial", Font.PLAIN, 24));
        g.drawString("Hello",  200, 200);
       }
</code>```

if it still doesn't work let me know in the comment! #YNWA

Title: Background not changing color

Body:
So I'm trying to change the background on a full screen game I'm making from a tutorial, I'm trying to change the background to green, but it stays black, what's wrong with the code?

Screen.java

package debels;

import java.awt.*;
import javax.swing.JFrame;

public class Screen {
    private GraphicsDevice vc;

    public Screen(){
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        vc = env.getDefaultScreenDevice();
    }

    public void setFullScreen(DisplayMode dm, JFrame window){
        window.setUndecorated(true);
        window.setResizable(false);
        vc.setFullScreenWindow(window);

        if (dm != null && vc.isDisplayChangeSupported()){
            try{
                vc.setDisplayMode(dm);
            }catch (Exception e){}
        }
    }

    public Window getFullScreen(){
        return vc.getFullScreenWindow();
    }

    public void restoreScreen(){
        Window w = vc.getFullScreenWindow();
        if (w != null){
            w.dispose();
        }
        vc.setFullScreenWindow(null);
    }
}

Main.java

package debels;

import java.awt.*;
import javax.swing.*;

public class Main extends JFrame{
    private static final long serialVersionUID = -7498470134154894036L;

    public static void main(String[] args){
        DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
        Main m = new Main();
        m.run(dm);
    }

    public void run(DisplayMode dm){
        setBackground(Color.GREEN);
        setForeground(Color.BLUE);
        setFont(new Font("Arial", Font.PLAIN, 24));

        Screen s = new Screen();
        try{
            s.setFullScreen(dm, this);
            try{
                Thread.sleep(5000);
            }catch(Exception e){}
        }finally{
            s.restoreScreen();
        }
    }

    public void paint(Graphics g){
        g.drawString("Hello",  200, 200);
    }
}

Body:
You just need to make 3 little changes and it will work. Follow these steps:

Step-1:Add getContentPane() to setBackgroud() which is present in the run() method

getContentPane().setBackground(Color.GREEN);

Step-2: Cut & paste below lines from run() method to paint() method.

getContentPane().setBackground(Color.GREEN);
setForeground(Color.BLUE);
setFont(new Font("Arial", Font.PLAIN, 24));

step-3: Add super.paint(g) in the starting of paint() method. the whole paint() method will look like this;

public void paint(Graphics g){
        super.paint(g);
        getContentPane().setBackground(Color.GREEN);
        setForeground(Color.BLUE);
        setFont(new Font("Arial", Font.PLAIN, 24));
        g.drawString("Hello",  200, 200);
       }

if it still doesn't work let me know in the comment! #YNWA


问:
keyword cant be an expression - sliders and selection menu
I'm trying to create code that will give the user the option on the primitive they'd like to create as well as the size of the object. Keyword cant be an expression is all I get but I can't find where it's referring to.

It was originally a syntax error inside of the cube object creation with a move command,I removed this and now its just this error

```<code>import maya.cmds as mt

def ShowUI():

    if mt.window("Main", exists = True):
        mt.deleteUI("Main")

    mt.window("Main", title = "Maya Primitives", w = 300, h = 500)
    mt.columnLayout("MainLayout", w = 300, h =500)
    mt.optionMenu("PolygonMenu", w = 250, label = "Polygon Selection:")
    mt.menuItem(label = "Sphere")
    mt.menuItem(label = "Cube")
    mt.menuItem(label = "Cylinder")
    mt.button("Create", label = "Create", w = 300, command=ObjectCreation)
    mt.button("Delete", label = "Delete", w = 300, command=DeleteButton)
    mt.button("Clear", label = "Clear", w = 300, command=SceneClear)
    mt.showWindow("Main")

def DeleteButton(*args):
    mt.delete()

def SceneClear(*args):
    mt.delete(all=True, c=True)

def ObjectCreation(*args):
    currentValue = mt.optionMenu("PolygonMenu", query=True, value=True)
    if currentValue == "Sphere":
        SphereRadius = mt.intSliderGrp(Sphradius, q = True, Value=True)
        finalSphere= mt.polySphere(r=SphereRadius, name = "Sphere", ch=False)

    elif currentValue == "Cube":
        CubeWidth = mt.intSliderGrp(CubeW, q = True, Value=True)
        CubeHeight = mt.intSliderGrp(CubeH, q = True, Value=True)
        CubeDepth = mt.intSliderGrp(CubeD, q = True, Value=True)
        finalSphere= mt.polyCube(w=CubeWidth, h=CubeHeight, d=CubeDepth, name = "Cube", ch=False)

    elif currentValue == "Cylinder":
        CyclinderRadius =  mt.intSliderGrp(Cylradius, q = True, Value=True)
        CyclinderHeight =  mt.intSliderGrp(CylH, q = True, Value=True)
        finalCylinder= mt.polyCylinder(r=CylinderRadius, h=CylinderHeight, name = "Cylinder", ch=False)

def SphereSlider():
    Sphradius = mt.intSliderGrp(1="Radius",min=0,max=25, field=True)

def CubeSlider():
    CubeW = mt.intSliderGrp(1="Width", min=0, max=25, field=True)
    CubeH = mt.intSliderGrp(1="Height", min=0, max=25, field=True)
    CubeD = mt.intSliderGrp(1="Depth", min=0, max=25, field=True)

def CylinderSlider():
    Cylradius = mt.intSliderGrp(1="Radius",min=0,max=25, field=True)
    CylH = mt.intSliderGrp(1="Height", min=0, max=25, field=True)

ShowUI()
</code>```

答:
It helps a lot if you post the exact error message with stack trace. In this case it says that the error occurs in line 46 in this line:

Sphradius = mt.intSliderGrp(1="Radius",min=0,max=25, field=True)

And it means that you use 1="Radius" is not correct because 1 is no a keyword. I suppose you wanted to call it label="Radius".

Body:
I'm trying to create code that will give the user the option on the primitive they'd like to create as well as the size of the object. Keyword cant be an expression is all I get but I can't find where it's referring to.

It was originally a syntax error inside of the cube object creation with a move command,I removed this and now its just this error

import maya.cmds as mt

def ShowUI():

    if mt.window("Main", exists = True):
        mt.deleteUI("Main")

    mt.window("Main", title = "Maya Primitives", w = 300, h = 500)
    mt.columnLayout("MainLayout", w = 300, h =500)
    mt.optionMenu("PolygonMenu", w = 250, label = "Polygon Selection:")
    mt.menuItem(label = "Sphere")
    mt.menuItem(label = "Cube")
    mt.menuItem(label = "Cylinder")
    mt.button("Create", label = "Create", w = 300, command=ObjectCreation)
    mt.button("Delete", label = "Delete", w = 300, command=DeleteButton)
    mt.button("Clear", label = "Clear", w = 300, command=SceneClear)
    mt.showWindow("Main")

def DeleteButton(*args):
    mt.delete()

def SceneClear(*args):
    mt.delete(all=True, c=True)

def ObjectCreation(*args):
    currentValue = mt.optionMenu("PolygonMenu", query=True, value=True)
    if currentValue == "Sphere":
        SphereRadius = mt.intSliderGrp(Sphradius, q = True, Value=True)
        finalSphere= mt.polySphere(r=SphereRadius, name = "Sphere", ch=False)

    elif currentValue == "Cube":
        CubeWidth = mt.intSliderGrp(CubeW, q = True, Value=True)
        CubeHeight = mt.intSliderGrp(CubeH, q = True, Value=True)
        CubeDepth = mt.intSliderGrp(CubeD, q = True, Value=True)
        finalSphere= mt.polyCube(w=CubeWidth, h=CubeHeight, d=CubeDepth, name = "Cube", ch=False)

    elif currentValue == "Cylinder":
        CyclinderRadius =  mt.intSliderGrp(Cylradius, q = True, Value=True)
        CyclinderHeight =  mt.intSliderGrp(CylH, q = True, Value=True)
        finalCylinder= mt.polyCylinder(r=CylinderRadius, h=CylinderHeight, name = "Cylinder", ch=False)

def SphereSlider():
    Sphradius = mt.intSliderGrp(1="Radius",min=0,max=25, field=True)

def CubeSlider():
    CubeW = mt.intSliderGrp(1="Width", min=0, max=25, field=True)
    CubeH = mt.intSliderGrp(1="Height", min=0, max=25, field=True)
    CubeD = mt.intSliderGrp(1="Depth", min=0, max=25, field=True)

def CylinderSlider():
    Cylradius = mt.intSliderGrp(1="Radius",min=0,max=25, field=True)
    CylH = mt.intSliderGrp(1="Height", min=0, max=25, field=True)

ShowUI()


问:
Simple way to combine many observables into one object
I need to build an object from couple of observables that comes from the ngrx state.

```<code>    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );
</code>```

How can i make this more readable and better code?

答:
I'd do this:

merge(
  obs1$.pipe(map((v) => ['obs1', v])),
  obs2$.pipe(map((v) => ['obs2', v])),
  obs3$.pipe(map((v) => ['obs3', v])),
  /* ... */
  obsN$.pipe(map((v) => ['obsN', v])),
).pipe(
  scan((acc, ([k, v])) => {
    acc[k] = v;

    return acc;
  }, {})
)
```

I believe that zip has more specific use-cases, other than just combining the observable's values into one object.

Body:
I need to build an object from couple of observables that comes from the ngrx state.

    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );

How can i make this more readable and better code?

Body:
I'd do this:

merge(
  obs1$.pipe(map((v) => ['obs1', v])),
  obs2$.pipe(map((v) => ['obs2', v])),
  obs3$.pipe(map((v) => ['obs3', v])),
  /* ... */
  obsN$.pipe(map((v) => ['obsN', v])),
).pipe(
  scan((acc, ([k, v])) => {
    acc[k] = v;

    return acc;
  }, {})
)

I believe that zip has more specific use-cases, other than just combining the observable's values into one object.


问:
MIPS Pipeline Stalls: SW after LW
I am confused as to how a Store Word Instruction coming after an LW using the same $rt causes a pipeline stall in MIPS.
Consider this block of code:

```<code>  lw $s0,  0($t0)
  sw $s0, 12($t0)
  lw $s1,  4($t0)
  sw $s1, 16($t0)
  lw $s2,  8($t0)
  sw $s2, 20($t0)
</code>```

Here 3 words are being shifted around in memory. For e.g in the first 2 lines, $s0 is loaded into ,
and then its contents are saved back in the memory. I'm not sure if the sw instruction required $s0 in EX stage or in MEM stage. if it is needed in MEM stage, wouldn't it be resolved just by forwarding without needing to stall the pipeline?

答:
Hypothetically, yes. Forwarding into the MEM stage directly would make it possible to execute dependent LW and SW back-to-back. As long as the loaded word is stored by the SW at least. It wouldn't be possible to have the SW use that loaded word as the base of the address without a pipeline bubble, otherwise it would require forwarding back in time.

But typically you would see a pipeline such as below (source: a model of a 5 stage pipelined MIPS in SIM-PL), with only one forwarder which feeds into EX. With a setup like that, there is no way to forward from LW into SW, the hardware required for it isn't there.

Title: MIPS Pipeline Stalls: SW after LW

Body:
I am confused as to how a Store Word Instruction coming after an LW using the same $rt causes a pipeline stall in MIPS.
Consider this block of code:

  lw $s0,  0($t0)
  sw $s0, 12($t0)
  lw $s1,  4($t0)
  sw $s1, 16($t0)
  lw $s2,  8($t0)
  sw $s2, 20($t0)

Here 3 words are being shifted around in memory. For e.g in the first 2 lines, $s0 is loaded into ,
and then its contents are saved back in the memory. I'm not sure if the sw instruction required $s0 in EX stage or in MEM stage. if it is needed in MEM stage, wouldn't it be resolved just by forwarding without needing to stall the pipeline?


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
Event Handlers are a very common source of non-obvious memory leaks.  If you subscribe to an event on object1 from object2, then do object2.Dispose() and pretend it doesn't exist (and drop out all references from your code), there is an implicit reference in object1's event that will prevent object2 from being garbage collected.

```<code>MyType object2 = new MyType();

// ...
object1.SomeEvent += object2.myEventHandler;
// ...

// Should call this
// object1.SomeEvent -= object2.myEventHandler;

object2.Dispose();
</code>```

This is a common case of a leak - forgetting to easily unsubscribe from events.  Of course, if object1 gets collected, object2 will get collected as well, but not until then.

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

Body:
Event Handlers are a very common source of non-obvious memory leaks.  If you subscribe to an event on object1 from object2, then do object2.Dispose() and pretend it doesn't exist (and drop out all references from your code), there is an implicit reference in object1's event that will prevent object2 from being garbage collected.

MyType object2 = new MyType();

// ...
object1.SomeEvent += object2.myEventHandler;
// ...

// Should call this
// object1.SomeEvent -= object2.myEventHandler;

object2.Dispose();

This is a common case of a leak - forgetting to easily unsubscribe from events.  Of course, if object1 gets collected, object2 will get collected as well, but not until then.


问:
How to bind context to React Functional Component
I have a function that I call from a child component callback. I'm trying to access some state variable but variables are undefined. I think the issue is when the child component callback the function context it not bind to the parent component. How to do this.

It is sure that myVariable is set before myFunciton is called.

```<code>const MyParentView = props => {

   const[myVariable, setMyVariable] = useState(undefined)

   const onTextFieldChange = val => {
       setMyVariable(val)
   }

   const myFunction = () => {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
   }

   return (
      <Input onChange={e => onTextFieldChange(e.target.value)}
      <MyChildComponent getData={()=>myFunction()}/>
   )
}
</code>```

Following is the child component ( The actual one )

```<code>// @flow

import React, { useEffect, useRef } from "react"
import { get } from "lodash"

type Props = {
  children: any,
  getData?: Function,
  threshold?: number
}

const InfiniteScroll = ({ children, getData, threshold = 0.9 }: Props) => {
  const listRef = useRef()

  useEffect(() => {
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  useEffect(() => {
    if (listRef.current) {
      const bottom = listRef.current.getBoundingClientRect().bottom
      const height =
        window.innerHeight || get(document, "documentElement.clientHeight")

      if (bottom <= height) {
        getData && getData()
      }
    }
  })

  const handleScroll = () => {
    const winScroll =
      get(document, "body.scrollTop") ||
      get(document, "documentElement.scrollTop")

    const height =
      get(document, "documentElement.scrollHeight") -
      get(document, "documentElement.clientHeight")

    const scrolled = winScroll / height
    if (scrolled >= threshold) {
      getData && getData()
    }
  }

  return <div ref={listRef}>{children}</div>
}

export default InfiniteScroll

</code>```

答:
Try returning a closure in your myFunction like this:

```<code>const myFunction = () => {
      return function() {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
      }
   }
</code>```

Body:
I have a function that I call from a child component callback. I'm trying to access some state variable but variables are undefined. I think the issue is when the child component callback the function context it not bind to the parent component. How to do this.

It is sure that myVariable is set before myFunciton is called.

const MyParentView = props => {

   const[myVariable, setMyVariable] = useState(undefined)

   const onTextFieldChange = val => {
       setMyVariable(val)
   }

   const myFunction = () => {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
   }

   return (
      <Input onChange={e => onTextFieldChange(e.target.value)}
      <MyChildComponent getData={()=>myFunction()}/>
   )
}

Following is the child component ( The actual one )

// @flow

import React, { useEffect, useRef } from "react"
import { get } from "lodash"

type Props = {
  children: any,
  getData?: Function,
  threshold?: number
}

const InfiniteScroll = ({ children, getData, threshold = 0.9 }: Props) => {
  const listRef = useRef()

  useEffect(() => {
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  useEffect(() => {
    if (listRef.current) {
      const bottom = listRef.current.getBoundingClientRect().bottom
      const height =
        window.innerHeight || get(document, "documentElement.clientHeight")

      if (bottom <= height) {
        getData && getData()
      }
    }
  })

  const handleScroll = () => {
    const winScroll =
      get(document, "body.scrollTop") ||
      get(document, "documentElement.scrollTop")

    const height =
      get(document, "documentElement.scrollHeight") -
      get(document, "documentElement.clientHeight")

    const scrolled = winScroll / height
    if (scrolled >= threshold) {
      getData && getData()
    }
  }

  return
{children}

}

export default InfiniteScroll

Body:
Try returning a closure in your myFunction like this:

const myFunction = () => {
      return function() {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
      }
   }


答:
You may combine two observables...to reach the response data when both have responded already.

```<code>fetchData(): Observable<any[]> {
    return combineLatest(
        this.observable1$(),
        this.observable2$()
    );
}
</code>```

duplicate: https://stackoverflow.com/revisions/62033110/1

Title: Simple way to combine many observables into one object

Body:
You may combine two observables...to reach the response data when both have responded already.

fetchData(): Observable<any[]> {
    return combineLatest(
        this.observable1$(),
        this.observable2$()
    );
}

duplicate: https://stackoverflow.com/revisions/62033110/1


问:
Query for tables with @ManyToMany relation(Hibernate)
I rewrite my SpringMVC app with using Hibernate.I try to make query for selecting lectures for group of students by id of group.with using SQL query(before I started rewrite it with using Hibernate)this query was:

```<code>"SELECT * FROM lectures WHERE id IN (SELECT lecture_id FROM lectures_groups WHERE group_id =?) ORDER BY date_of_lecture"
</code>```

I have Lecture and Group etities:

```<code>@Entity
@Table(name = "lectures")
public class Lecture {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "lecture_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
    private List<Group> groups = new ArrayList<>();
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teacher_id")
    private Teacher teacher;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "subject_id")
    private Subject subject;
    @Column(name = "date_of_lecture")
    private LocalDateTime date;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "audience")
    private Audience audience;

    public Lecture() {

    }
//getters setters
}
</code>```

and:

```<code>@Entity
@Table(name = "groups")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "group_name")
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cathedra_id", referencedColumnName = "id")
    private Cathedra cathedra;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "lecture_id"))
    private List<Lecture> lectures = new ArrayList<>();

    public Group() {

    }
//getters setters
}
</code>```

I tried somthing like:

```<code>List<Lecture> lectures = session.createQuery("select l from lectures l join l.groups g where g.id=:groupId")
                .setParameter("groupId", group.getId())
                .list();
</code>```

but I get Exception: org.hibernate.hql.internal.ast.QuerySyntaxException: lectures is not mapped
So how can i do it?

答:
In hql query you need to provide the name of the entity in the query instead of the table name. So in your case, you should replace lectures with Lecture in the query.

List<Lecture> lectures = session.createQuery("select l from Lecture l join l.groups g where g.id=:groupId")
                .setParameter("groupId", group.getId())
                .list();
```

Body:
I rewrite my SpringMVC app with using Hibernate.I try to make query for selecting lectures for group of students by id of group.with using SQL query(before I started rewrite it with using Hibernate)this query was:

"SELECT * FROM lectures WHERE id IN (SELECT lecture_id FROM lectures_groups WHERE group_id =?) ORDER BY date_of_lecture"

I have Lecture and Group etities:

@Entity
@Table(name = "lectures")
public class Lecture {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "lecture_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
    private List<Group> groups = new ArrayList<>();
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teacher_id")
    private Teacher teacher;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "subject_id")
    private Subject subject;
    @Column(name = "date_of_lecture")
    private LocalDateTime date;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "audience")
    private Audience audience;

    public Lecture() {

    }
//getters setters
}

and:

@Entity
@Table(name = "groups")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "group_name")
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cathedra_id", referencedColumnName = "id")
    private Cathedra cathedra;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "lecture_id"))
    private List<Lecture> lectures = new ArrayList<>();

    public Group() {

    }
//getters setters
}

I tried somthing like:

List<Lecture> lectures = session.createQuery("select l from lectures l join l.groups g where g.id=:groupId")
                .setParameter("groupId", group.getId())
                .list();

but I get Exception: org.hibernate.hql.internal.ast.QuerySyntaxException: lectures is not mapped
So how can i do it?


问:
data_generator.flow_from_directory() function reads 4 images out of 20
I have 20 images in ./data/pets/test path but function return only 4 out of all.

```<code>data_generator = ImageDataGenerator(
validation_split=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

data_generator = ImageDataGenerator(
validation_split=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
</code>```

Thank you.

答:
According to this keras document</p>

```<code>image_gen_1 = data_generator_1.flow_from_directory('input1_dir',
                                shuffle=False,
                                class_mode=None)

image_gen_2 = data_generator_2.flow_from_directory('input2_dir',
                                shuffle=False,
                                class_mode=None)
</code>```

Body:
I have 20 images in ./data/pets/test path but function return only 4 out of all.

data_generator = ImageDataGenerator(
validation_split=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

data_generator = ImageDataGenerator(
validation_split=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

Thank you.

Body:
According to this keras document

image_gen_1 = data_generator_1.flow_from_directory('input1_dir',
                                shuffle=False,
                                class_mode=None)

image_gen_2 = data_generator_2.flow_from_directory('input2_dir',
                                shuffle=False,
                                class_mode=None)


答:
Advantages of bit flags:

1) The flags attribute gives you nicer ToString() behaviour than an array of an enum.

2) You can store multiple values in one variable (hence why you don't need an array). This could be important in a memory bound operation.

3) The method Enum.HasFlag exists so you don't actually have to implement your static class.

Disadvantages:

1) You cannot store multiple instances of the same value in the flag - on/off. Your array could have multiple instances of the same value.

2) Any = 0 value will have to be checked separately if you want one.

3) In my option it's not always as clear what you're doing when using bit flags - there's an extra element of knowledge that you need.

Title: Is there any reason to use enum params over bit flags in c#?


问:
GCC inline assembly error: no such instruction: `stosd'
Oh man, I've got yet another error while compiling the following inline assembly code (with -fasm-blocks) under GCC:

```<code>_asm
{
    mov ecx, esi
    shr ecx, 2
    rep stosd
};
</code>```

GCC understands other stos instructions, why won't it accept stosd???

答:
seeing as your using intel syntax, just go for the explicit version of the STOS command: REP STOS DWORD PTR:[EDI].

and iirc under gcc, stosd is called stosl.

Body:
Oh man, I've got yet another error while compiling the following inline assembly code (with -fasm-blocks) under GCC:

_asm
{
    mov ecx, esi
    shr ecx, 2
    rep stosd
};

GCC understands other stos instructions, why won't it accept stosd???


问:
How to use Python XML findall to find '<v:imagedata r:id="rId7" o:title="1-REN"/>'
I'm trying to do a find all from a Word document for <v:imagedata r:id="rId7" o:title="1-REN"/> with namespace xmlns:v="urn:schemas-microsoft-com:vml" and I cannot figure out what on earth the syntax is.

The docs only cover the very straight forward case and with the URN and VML combo thrown in I can't seem to get any of the examples I've seen online to work. Does anyone happen to know what it is?

I'm trying to do something like this:

```<code>namespace = {'v': "urn:schemas-microsoft-com:vml"}

results = ET.fromstring(xml).findall("imagedata", namespace)
for image_id in results:
    print(image_id)
</code>```

Edit: What @aneroid wrote is 1000% the right answer and super helpful. You should upvote it. That said, after understanding all that - I went with the BS4 answer because it does the entire job in two lines exactly how I need it to . If you don't actually care about the namespaces it seems waaaaaaay easier.

答:
With ElementTree in Python 3.8, you can simply use a wildcard ({*}) for the namespace:

```<code>results = ET.fromstring(xml).findall(".//{*}imagedata")
</code>```

Note the .// part, which means that the whole document (all descendants) is searched.

Body:
I'm trying to do a find all from a Word document for <v:imagedata r:id="rId7" o:title="1-REN"/> with namespace xmlns:v="urn:schemas-microsoft-com:vml" and I cannot figure out what on earth the syntax is.

The docs only cover the very straight forward case and with the URN and VML combo thrown in I can't seem to get any of the examples I've seen online to work. Does anyone happen to know what it is?

I'm trying to do something like this:

namespace = {'v': "urn:schemas-microsoft-com:vml"}

results = ET.fromstring(xml).findall("imagedata", namespace)
for image_id in results:
    print(image_id)

Edit: What @aneroid wrote is 1000% the right answer and super helpful. You should upvote it. That said, after understanding all that - I went with the BS4 answer because it does the entire job in two lines exactly how I need it to . If you don't actually care about the namespaces it seems waaaaaaay easier.

Body:
With ElementTree in Python 3.8, you can simply use a wildcard ({*}) for the namespace:

results = ET.fromstring(xml).findall(".//{*}imagedata")

Note the .// part, which means that the whole document (all descendants) is searched.


问:
Getting two buttons next to each other
I am having a problem with my design.

I have two buttons on my product page. However because one is in a form, they are on top of each other(see image ).

I want to get the two buttons next to each other. Can someone help me out, please ? Below I added my HTML and CSS code.

Thanks in advance!

HTML:

```<code><!DOCTYPE HTML>
<div class="container text-center">
            <div class="sale">
                <h1>On Sale</h1>
                <p class="text-secondary">
                    We have new sales promotions online for a short period of time every day. We offer products from
                    popular labels and luxury brands in the lifestyle segment up to 75% cheaper than the
                    recommended retail price.
                </p>
            </div>
</div>

        <section class="on-sale">
            <div class="container">
                <div class="row">

                <?php
                    for($i = 0; $i < $countProductItems && $i < 4; $i++){
                        ?>
                        <div class="col-md-3">
                        <div class="product-top">
                        <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><img src="<?php echo ($saleProducts[$i]['imgProduct1']);?>" class="img-fluid" alt="Product1"/></a>
                            <div class="overlay-right text-center">
                                <button type="button" class="btn btn-secondary" title="Quick Shop">
                                <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><i class="fa fa-eye text-white"></i></a>
                                </button>
                                <form action="includes/shopping-cart.inc.php?action=add&id=<?php echo ($saleProducts[$i]['ID'])?>" method="post">
                                    <input class="text-center" type="hidden" name="quantity" value="1"/>
                                    <input type="hidden" name="index-page" value="index">
                                    <input type="hidden" name="product-name" value="<?php echo ($saleProducts[$i]['strProductNaam']); ?>">
                                    <input type="hidden" name="product-price" value="<?php echo ($saleProducts[$i]['strSalePrijs']); ?>">
                                    <button type="submit" class="btn btn-secondary " title="Add to cart" name="add_to_cart"><i class="fa fa-shopping-cart"></i></button>
                                </form>
                            </div>
                        </div>
                        <div class="product-bottom text-center">
                        <p>
                                <?php rating_star(($saleProducts[$i]['RatingStar'])) ?>
                            </p>
                            <p><h3><?php echo ($saleProducts[$i]['strProductNaam']); ?></h3></p>
                            <?php sale_product(($saleProducts[$i]['intPrijs']), ($saleProducts[$i]['strSalePrijs']))?>
                        </div>
                    </div>
                    <?php
                    }
                ?>

                </div>
            </div>
        </section>
</html>
</code>```

CSS:

```<code>.container .sale{
    padding: 3rem 0;
    }

    .container .sale{
        font-family: var(--gugi);
    }

    .container .sale{
        padding: 0.5% 25%;
        font-size: 0.9em;
    }

.on-sale{
    margin: 50px 0;
}

.on-sale img{
    width: 100%;
    padding: 20px;
    transition: 1s;
    cursor: pointer;
}

.on-sale img:hover{
    transform: scale(1.1);
}

.product-top{
    width:100%;
    display: inline-block;

}

.product-bottom .fa{
    color: orange;
    font-size: 10px;
}

.product-bottom h3{
    font-size: 20px;
    font-weight: bold;
}

.product-bottom h5{
    font-size: 15px;
    padding-bottom: 10px;
}

.make_red {
        color: red;
}
</code>```

// codefilling text[error] - nfnjsnfjsfnbjkdsnfdsfndjsfbjabsdjhbgdgabadsg

答:
You can give the form a display: inline in your css.
Default display is block for a form

Title: Getting two buttons next to each other

Body:
I am having a problem with my design.

I have two buttons on my product page. However because one is in a form, they are on top of each other(see image ).

I want to get the two buttons next to each other. Can someone help me out, please ? Below I added my HTML and CSS code.

Thanks in advance!

HTML:

<!DOCTYPE HTML>

On Sale

                    We have new sales promotions online for a short period of time every day. We offer products from
                    popular labels and luxury brands in the lifestyle segment up to 75% cheaper than the
                    recommended retail price.

                <?php
                    for($i = 0; $i < $countProductItems && $i < 4; $i++){
                        ?>

                        <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><img src="<?php echo ($saleProducts[$i]['imgProduct1']);?>" class="img-fluid" alt="Product1"/>

                                <button type="button" class="btn btn-secondary" title="Quick Shop">
                                <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST">
                                </button>
                                <form action="includes/shopping-cart.inc.php?action=add&id=<?php echo ($saleProducts[$i]['ID'])?>" method="post">
                                    <input class="text-center" type="hidden" name="quantity" value="1"/>
                                    <input type="hidden" name="index-page" value="index">
                                    <input type="hidden" name="product-name" value="<?php echo ($saleProducts[$i]['strProductNaam']); ?>">
                                    <input type="hidden" name="product-price" value="<?php echo ($saleProducts[$i]['strSalePrijs']); ?>">
                                    <button type="submit" class="btn btn-secondary " title="Add to cart" name="add_to_cart"></button>
                                </form>

                                <?php rating_star(($saleProducts[$i]['RatingStar'])) ?>

<?php echo ($saleProducts[$i]['strProductNaam']); ?>

                            <?php sale_product(($saleProducts[$i]['intPrijs']), ($saleProducts[$i]['strSalePrijs']))?>

                    <?php
                    }
                ?>

CSS:

.container .sale{
    padding: 3rem 0;
    }

    .container .sale{
        font-family: var(--gugi);
    }

    .container .sale{
        padding: 0.5% 25%;
        font-size: 0.9em;
    }

.on-sale{
    margin: 50px 0;
}

.on-sale img{
    width: 100%;
    padding: 20px;
    transition: 1s;
    cursor: pointer;
}

.on-sale img:hover{
    transform: scale(1.1);
}

.product-top{
    width:100%;
    display: inline-block;

}

.product-bottom .fa{
    color: orange;
    font-size: 10px;
}

.product-bottom h3{
    font-size: 20px;
    font-weight: bold;
}

.product-bottom h5{
    font-size: 15px;
    padding-bottom: 10px;
}

.make_red {
        color: red;
}

// codefilling text[error] - nfnjsnfjsfnbjkdsnfdsfndjsfbjabsdjhbgdgabadsg


问:
Match all lines with a pattern after a text until pattern matching failure regex
I have a text:

```<code>
{{Verkleinerungsformen}}
:[1] [[Äpfelchen]], [[Äpfelein]], [[Äpflein]]

{{Oberbegriffe}}
:[1] [[Kernobst]], [[Obst]]; [[Frucht]]
:[4] [[Kot]]
:[7] [[Gut]]

{{Unterbegriffe}}
:[1] [[Augustapfel]], [[Bohnapfel]], [[Bratapfel]], [[Essapfel]], [[Fallapfel]],

</code>```

I'm interested in extracting all items under {{Oberbegriffe}} that have the pattern [[Text]]
including all lines until it reach another line that does not have :[NUMBER-HERE] at the begin

so in the above example it should return an array of these strings:

Kernobst, Obst, Frucht, Kot, Gut

what I have tried is:

re.search(r'{{Oberbegriffe}}\n(?::?\n)?([^\n]+)', text)

But it matches only the full first line. It's ok if there is a way to extract all lines with the pattern and it retruns this  string

```<code>:[1] [[Kernobst]], [[Obst]]; [[Frucht]]
:[4] [[Kot]]
:[7] [[Gut]]
</code>```

答:
You may extract the blocks using

```<code>(?m)^{{Oberbegriffe}}(?:\n:\[\d+].*)*
</code>```

See the regex demo

Then, use \[\[([^][]+)]] pattern to extract the values you need. See this regex demo.

Regex details

(?m) - an inline modifier, same as re.M / re.MULTILINE

^ - start of a line

{{Oberbegriffe}}  - literal text

(?:\n:\[\d+].*)* - 0 or more repetitions of a newline followed with :[, then 1+ digits, ], and then any 0 or more characters other than line break chars, as many as possible.

The second regex - \[\[([^][]+)]] - matches [[, then capturing group #1 matching any 1 or more chars other than [ and ], and then ]].

In Python:

```<code>with open(filepath, 'r') as fr:
  blocks = re.findall(r'^{{Oberbegriffe}}(?:\n:\[\d+].*)*', fr.read(), flags=re.M)
  print([re.findall(r'\[\[([^][]+)]]', block) for block in blocks])
</code>```

Body:
I have a text:

{{Verkleinerungsformen}}
:[1] [[Äpfelchen]], [[Äpfelein]], [[Äpflein]]

{{Oberbegriffe}}
:[1] [[Kernobst]], [[Obst]]; [[Frucht]]
:[4] [[Kot]]
:[7] [[Gut]]

{{Unterbegriffe}}
:[1] [[Augustapfel]], [[Bohnapfel]], [[Bratapfel]], [[Essapfel]], [[Fallapfel]],

I'm interested in extracting all items under {{Oberbegriffe}} that have the pattern [[Text]]
including all lines until it reach another line that does not have :[NUMBER-HERE] at the begin

so in the above example it should return an array of these strings:

Kernobst, Obst, Frucht, Kot, Gut

what I have tried is:

re.search(r'{{Oberbegriffe}}\n(?::?\n)?([^\n]+)', text)

But it matches only the full first line. It's ok if there is a way to extract all lines with the pattern and it retruns this  string

:[1] [[Kernobst]], [[Obst]]; [[Frucht]]
:[4] [[Kot]]
:[7] [[Gut]]

Body:
You may extract the blocks using

(?m)^{{Oberbegriffe}}(?:\n:\[\d+].*)*

See the regex demo

Then, use \[\[([^][]+)]] pattern to extract the values you need. See this regex demo.

Regex details

(?m) - an inline modifier, same as re.M / re.MULTILINE

^ - start of a line

{{Oberbegriffe}}  - literal text

(?:\n:\[\d+].*)* - 0 or more repetitions of a newline followed with :[, then 1+ digits, ], and then any 0 or more characters other than line break chars, as many as possible.

The second regex - \[\[([^][]+)]] - matches [[, then capturing group #1 matching any 1 or more chars other than [ and ], and then ]].

In Python:

with open(filepath, 'r') as fr:
  blocks = re.findall(r'^{{Oberbegriffe}}(?:\n:\[\d+].*)*', fr.read(), flags=re.M)
  print([re.findall(r'\[\[([^][]+)]]', block) for block in blocks])


问:
socket with python flask and ajax call
I have scenario where I want to use sockets to wrap my API calls and not available to hit directly the api in browser and get data.

index.html :

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Report</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css"/>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>

  <script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>

  <script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
  <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>

</head>
<body style="background-color:mintcream;">
<div ><span style="font-family: sans-serif;font-size: x-large;al:center;">reportyu</span> <br> <br>

<table id="example" class="table table-striped table-bordered" style="width:100%;">
        <thead>
            <tr>
                <th>Lame</th>
                <th>IAr</th>
                <th>Hee</th>
                <th>ED</th>
                <th>SPs</th>
                <th>Ts</th>
                <th>SD</th>
                <th>Rs</th>
                <th>Ld</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
               <th>Lame</th>
                <th>IAr</th>
                <th>Hee</th>
                <th>ED</th>
                <th>SPs</th>
                <th>Ts</th>
                <th>SD</th>
                <th>Rs</th>
                <th>Ld</th>
            </tr>
        </tfoot>
    </table>
<script>
function setupData() {
    $(document).ready(function () {
        $('#example').DataTable({
            responsive: true,
            "ajax": {
                "url": "/index_get_data",
                "dataType": "json",
                "dataSrc": "data",
                "contentType":"application/json"
            },
            "columns": [
                {"data": "L_name"},
                {"data": "Ia_r"},
                {"data": "He_e"},
                {"data": "e_d",
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<a href='//abc.app.com/"+oData.e_d+"'>"+oData.e_d+"</a>");
                    }
                },
                {"data": "s_ps"},
                {"data": "t_s"},
                {"data": "s_d",
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<a href='//app2.com/"+oData.s_d+"'>"+oData.s_d+"</a>");
                    }
                },
                {"data": "R_n",
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<a href='//sshse.com/"+oData.R_n+"'>"+oData.R_n+"</a>");
                    }
                },
                {"data": "l_d"}

            ],
            dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'pdfHtml5',
                        orientation: 'landscape',
                        pageSize: 'LEGAL'
                    },
                    'copyHtml5',
                    'excelHtml5'
        ]
        });

    });
}
$( window ).on( "load", setupData );
</script>
</body>
</html>
</code>```

here is my app.py :

```<code>from flask import Flask, render_template, jsonify
import json

app = Flask(__name__)

@app.route('/index')
@app.route('/')
def index():
  return render_template('index.html')

@app.route('/index_get_data')
def stuff():
  # Assume data comes from somewhere else
  with open('crtp.json') as test_file:
    data = json.load(test_file)
  return jsonify(data)

if __name__ == '__main__':
  app.run()
</code>```

This works as expected but when I hit the url localhost:5000 in browser I am also able to see the API call in network tab of the browser and then if I hit the endpoint localhost:5000/index_get_data
I am able to use the API openly.
I have explored options of sending token based auth in headers and basic auth but still the response can be derived and the API is still open for use which I want to restrict , I came across flask-sockets which seems to help here but not sure how can I implement this here.

Any help regarding this or any other approach to achieve this would be great.

答: It isn't clear what you really are trying to do, and why you don't want 'browsers' to be able to see your endpoints. Flask (and browsers) use HTTP and HTTPS to communicate. There are huge amounts of information, packages, etc about how all that works - and if you are interested in any sort of interoperability - you should stick to well-established protocols. You might be asking how to SECURE your endpoints such that only clients that have appropriate credentials can access your site. That is what packages such as Flask-Security-Too, Flask-Dance, Flask-Login all provide. Flask itself doesn't provide any endpoint protection</p>

Title: socket with python flask and ajax call

Body:
I have scenario where I want to use sockets to wrap my API calls and not available to hit directly the api in browser and get data.

index.html :

<!DOCTYPE html>

  <title>Report</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css"/>

reportyu

                Lame
                IAr
                Hee
                ED
                SPs
                Ts
                SD
                Rs
                Ld

               Lame
                IAr
                Hee
                ED
                SPs
                Ts
                SD
                Rs
                Ld

here is my app.py :

from flask import Flask, render_template, jsonify
import json

app = Flask(__name__)

@app.route('/index')
@app.route('/')
def index():
  return render_template('index.html')

@app.route('/index_get_data')
def stuff():
  # Assume data comes from somewhere else
  with open('crtp.json') as test_file:
    data = json.load(test_file)
  return jsonify(data)

if __name__ == '__main__':
  app.run()

This works as expected but when I hit the url localhost:5000 in browser I am also able to see the API call in network tab of the browser and then if I hit the endpoint localhost:5000/index_get_data
I am able to use the API openly.
I have explored options of sending token based auth in headers and basic auth but still the response can be derived and the API is still open for use which I want to restrict , I came across flask-sockets which seems to help here but not sure how can I implement this here.

Any help regarding this or any other approach to achieve this would be great.


问:
Java Special Character Handling
I need to send a string to server. That string is having some special characters.

Example,

```<code>String abc = "ABC Farmacéutica Corporation";
</code>```

When I am sending it, It is converted into, ABC Farmace@utica Corporation.

I Tried using UTF-8 encoding. it is giving output as ABC+Farmac%C3%A9utica+Corporation

please suggest me how to convert the data in java side.

答:
It entirely depends on how the server is set up to receive the string in the first place. Your second example is applying URL-encoding using UTF-8 where required, by the look of things. That might be appropriate - or it might not.

If the data is within XML, for example, you shouldn't need to do anything special - whatever XML API you use should handle all of this transparently.

If you can give more details about the protocol you're using to talk to the server, we may be able to help more.

Title: Java Special Character Handling

Body:
I need to send a string to server. That string is having some special characters.

Example,

String abc = "ABC Farmacéutica Corporation";

When I am sending it, It is converted into, ABC Farmace@utica Corporation.

I Tried using UTF-8 encoding. it is giving output as ABC+Farmac%C3%A9utica+Corporation

please suggest me how to convert the data in java side.


问:
How do you put an onclick on a js button
I have some js created buttons from GeeksforGeeks, but I don't know how to put on click on the buttons. I can create a button using the code I found online, but there was no explanation on how to make that button have on click function</p>

答:
The onclick="java_script_function()" attribute can be used for handling click event on a button.

Here is a working example:

```<code><!DOCTYPE html>
<html>
    <body>
        <button onclick="clickDemo()">On-click Demo</button>
        <hr>
        <span id="result"></span>
        <script>
            function clickDemo() {
                document.getElementById("result").innerHTML = "Button was clicked";
            }
        </script>
    </body>
</html>
</code>```

Output:

More information:

https://www.w3schools.com/jsref/event_onclick.asp

Body:
The onclick="java_script_function()" attribute can be used for handling click event on a button.

Here is a working example:

<!DOCTYPE html>
<html>
    <body>
        <button onclick="clickDemo()">On-click Demo</button>
        <hr>
        <span id="result"></span>
        <script>
            function clickDemo() {
                document.getElementById("result").innerHTML = "Button was clicked";
            }
        </script>
    </body>
</html>

Output:

More information:

https://www.w3schools.com/jsref/event_onclick.asp


问:
change dataTables page number in resize
I'm using dataTables (https://datatables.net) and trying to do a responsive page number, I need this:

Desktop:
first prev 1 2 3 4 5 next last

Mobile:
first prev 1 2 3 next last

Actually with my code I get this on mobile, nothing change:
first prev 1 2 3 4 5 next last

This is my code:

```<code>$(window).resize(function () {
   if ($(this).outerWidth() < 768){
      // change the dataTable pageLength in here
      $.fn.DataTable.ext.pager.numbers_length = 3;
   } else {
      // default pageLength
      $.fn.DataTable.ext.pager.numbers_length = 5;
   }
});
</code>```

答:
Datatables Pagination Pager Adjust numbers length

A good alternative would be to pass the call every time you resize the window, thus avoiding errors with the datatables

```<code>// Adjust Pagination number page
$.dt_adjust_pager_number = function(dtable){
    var ipag = $.fn.DataTable.ext.pager.numbers_length,i,
      w = document.documentElement.clientWidth;
    // window.screen.width -> This only tends to identify that the customer at a wide screen is not advisable to use it for a responsive
    if (w < 768) {
        i = 4;
    } else if (w <= 1024) {
        i = 5;
    } else if ( w > 1024) {
        i = 7;
    }
    //console.log(ipag,i);
    if (i && ipag != i ){
        $.fn.DataTable.ext.pager.numbers_length = i;
        if (typeof dtable == 'object'){
            dtable.draw( 'page' );
            //Other alternatives:
            //dtable.columns.adjust().draw( 'page' );
            //dtable.page(0).draw( 'page' );
        }
    }
};
// init ready window
$.dt_adjust_pager_number();

var osTable = $('#table').DataTable(); // $.fn.dataTable.tables();

$(window).resize(function () {
    if (window.tmdoit){
        window.clearTimeout(window.tmdoit);
    }
    window.tmdoit = window.setTimeout(function(){
        $.dt_adjust_pager_number(osTable);
    },400);
});
</code>```

Title: change dataTables page number in resize

Body:
I'm using dataTables (https://datatables.net) and trying to do a responsive page number, I need this:

Desktop:
first prev 1 2 3 4 5 next last

Mobile:
first prev 1 2 3 next last

Actually with my code I get this on mobile, nothing change:
first prev 1 2 3 4 5 next last

This is my code:

$(window).resize(function () {
   if ($(this).outerWidth() < 768){
      // change the dataTable pageLength in here
      $.fn.DataTable.ext.pager.numbers_length = 3;
   } else {
      // default pageLength
      $.fn.DataTable.ext.pager.numbers_length = 5;
   }
});

Body:
Datatables Pagination Pager Adjust numbers length

A good alternative would be to pass the call every time you resize the window, thus avoiding errors with the datatables

// Adjust Pagination number page
$.dt_adjust_pager_number = function(dtable){
    var ipag = $.fn.DataTable.ext.pager.numbers_length,i,
      w = document.documentElement.clientWidth;
    // window.screen.width -> This only tends to identify that the customer at a wide screen is not advisable to use it for a responsive
    if (w < 768) {
        i = 4;
    } else if (w <= 1024) {
        i = 5;
    } else if ( w > 1024) {
        i = 7;
    }
    //console.log(ipag,i);
    if (i && ipag != i ){
        $.fn.DataTable.ext.pager.numbers_length = i;
        if (typeof dtable == 'object'){
            dtable.draw( 'page' );
            //Other alternatives:
            //dtable.columns.adjust().draw( 'page' );
            //dtable.page(0).draw( 'page' );
        }
    }
};
// init ready window
$.dt_adjust_pager_number();

var osTable = $('#table').DataTable(); // $.fn.dataTable.tables();

$(window).resize(function () {
    if (window.tmdoit){
        window.clearTimeout(window.tmdoit);
    }
    window.tmdoit = window.setTimeout(function(){
        $.dt_adjust_pager_number(osTable);
    },400);
});


问:
Refactoring Express code and cannot figure out variable scope
I hope this is not a silly question.  I have a homepage route that loads up a lot of mongo databases, and I originally had it loop through the mongo databases and add them to an array that was rendered to a webpage.  However, the databases have become more complicated and they need to be populated, so I can no longer use a loop to accomplish this, and needed to refactor to getting the databases individually.  However, I seem to be having problems with the variable's scopes, as they are always returned as empty outside of the .find function.
My original code was this:

```<code>    const collections = [User, Ticket, Client, Job, Transaction];
    let endCollections = [];
    for (let i = 0; i < collections.length; i++){
        await collections[i].find({}, function(err, foundCollection){
            if (err) {
                console.log(err);
            } else {
                endCollections[i] = foundCollection;
            }
        });
    }
    res.render("dashboard", {transactions: endCollections[4], clients: endCollections[2], tickets: endCollections[1], jobs: endCollections[3]});
</code>```

And this worked fine.  But I need to populate the individual databases, so this was no longer useful.  I rewrote it out to populate, but I am having problems changing the global variables inside of the functions.  Here is the new code I am trying:

```<code>    let transactions = [],
    clients = [],
    jobs = [],
    tickets = [];

    await Transaction.find({}).populate("job").populate("client").populate("deposited_by_user").exec(function(err, foundTransactions){
        if(err){
            console.log(err)
        } else {
            for (let i = 0; i < foundTransactions.length; i++){
                foundTransactions[i]["transaction_info"]["new_amount"] = numberWithCommas(foundTransactions[i]["transaction_info"]["amount"]);
            }
        }
        transactions = foundTransactions;
    });

    await Client.find({}).populate("transactions").populate("jobs").exec(function(err, foundClients){
        if(err){
            console.log(err)
        }
        clients = foundClients;
    });

    await Ticket.find({}).populate("created_by").populate("assigned_user").populate("completed_by_user").exec(function(err, foundTickets){
        if(err){
            console.log(err)
        }
        tickets = foundTickets;
    });

    await Job.find({}).populate("created_by").populate("client").populate("transactions").exec(function(err, foundJobs){
        if(err){
            console.log(err)
        }
        jobs = foundJobs;
    });

    res.render("dashboard", {transactions: transactions, clients: clients, tickets: tickets, jobs: jobs});
</code>```

For example, if I console.log "jobs" right after the line jobs = foundJobs;, it will show the jobs array being populated.  However, if I console.log "jobs" right before the res.render, it shows it as empty.  Considering the global variable endCollections in my original code seemed to be changed within the functions before, I am unsure why my new code does not do the same as everything is returned empty.  I know that somehow the scope of the variable is what is wrong here, but I cannot see how.  Is there something obvious I am missing?  Thanks.

答:
Here now the answer so it is not buried in the post's comments.

After reading the docs, I think you should either use await with an empty exec() or use exec(callback).

What happens when you use both is that exec(callback) sees u passed a callback, it asynchronously executes your query and adds the callback to the promise.then of the query promise to be called once the query promise is settled. Then it immediately returns but it does not return the query promise since you passed a callback. The await is simply awaiting the normal (probably void/undefined) return of the function which is why removing it does not change anything.

After awaiting the return of the function, res.render executes and some time after that, the promise that had been created in the exec(callback) call settles and the callback you passed is executed.

So what is the appropriate way of fixing this? I would encourage you to read deeper into async/awai, promises, and the docs I linked above and find it out yourself before you read on, but since the solution is quite simple I'll leave it here.

// your variable declarations
try {
    const foundTransactions = await Transaction.find({}).populate("job").populate("client").populate("deposited_by_user").exec();
    // your for loop
    transactions = foundTransactions;
    // same for the other calls
     tickets: tickets, jobs: jobs});
catch (e) {console.log(e);}
res.render("dashboard", {transactions: transactions, clients: clients,...
```

Body:
I hope this is not a silly question.  I have a homepage route that loads up a lot of mongo databases, and I originally had it loop through the mongo databases and add them to an array that was rendered to a webpage.  However, the databases have become more complicated and they need to be populated, so I can no longer use a loop to accomplish this, and needed to refactor to getting the databases individually.  However, I seem to be having problems with the variable's scopes, as they are always returned as empty outside of the .find function.
My original code was this:

    const collections = [User, Ticket, Client, Job, Transaction];
    let endCollections = [];
    for (let i = 0; i < collections.length; i++){
        await collections[i].find({}, function(err, foundCollection){
            if (err) {
                console.log(err);
            } else {
                endCollections[i] = foundCollection;
            }
        });
    }
    res.render("dashboard", {transactions: endCollections[4], clients: endCollections[2], tickets: endCollections[1], jobs: endCollections[3]});

And this worked fine.  But I need to populate the individual databases, so this was no longer useful.  I rewrote it out to populate, but I am having problems changing the global variables inside of the functions.  Here is the new code I am trying:

    let transactions = [],
    clients = [],
    jobs = [],
    tickets = [];

    await Transaction.find({}).populate("job").populate("client").populate("deposited_by_user").exec(function(err, foundTransactions){
        if(err){
            console.log(err)
        } else {
            for (let i = 0; i < foundTransactions.length; i++){
                foundTransactions[i]["transaction_info"]["new_amount"] = numberWithCommas(foundTransactions[i]["transaction_info"]["amount"]);
            }
        }
        transactions = foundTransactions;
    });

    await Client.find({}).populate("transactions").populate("jobs").exec(function(err, foundClients){
        if(err){
            console.log(err)
        }
        clients = foundClients;
    });

    await Ticket.find({}).populate("created_by").populate("assigned_user").populate("completed_by_user").exec(function(err, foundTickets){
        if(err){
            console.log(err)
        }
        tickets = foundTickets;
    });

    await Job.find({}).populate("created_by").populate("client").populate("transactions").exec(function(err, foundJobs){
        if(err){
            console.log(err)
        }
        jobs = foundJobs;
    });

    res.render("dashboard", {transactions: transactions, clients: clients, tickets: tickets, jobs: jobs});

For example, if I console.log "jobs" right after the line jobs = foundJobs;, it will show the jobs array being populated.  However, if I console.log "jobs" right before the res.render, it shows it as empty.  Considering the global variable endCollections in my original code seemed to be changed within the functions before, I am unsure why my new code does not do the same as everything is returned empty.  I know that somehow the scope of the variable is what is wrong here, but I cannot see how.  Is there something obvious I am missing?  Thanks.


问:
spotipy query does not return resultset from spotify
I have the following code, but there is an empty response, while the combi title / artist is in spotify.
Is there anybody who can help me?

If i do the same for one of us / abba as track / artist it gives results.

```<code>from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import sys
import pprint

artist = 'karel gott'
track = 'eine liebe ist viele tranen wert'

if len(sys.argv) > 1:
    search_str = sys.argv[1]
else:
    search_str = 'artist:{} track:{}'.format(artist, track)

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
result = sp.search(q=search_str)
pprint.pprint(result)
</code>```

答:
By default the API will search through songs in the US market, that means songs that can legally only be listened by US customers.

I found that the song you are looking for is available in countries across Europe. For that song I get results in the GB as well as FR markets, and even more results in the german one.

So, just specify the market where you are using Spotify from:

```<code>sp.search(q=search_str, market="DE")
</code>```

Unfortunately I am not aware of an easy way to search through all markets at once.

Body:
I have the following code, but there is an empty response, while the combi title / artist is in spotify.
Is there anybody who can help me?

If i do the same for one of us / abba as track / artist it gives results.

from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import sys
import pprint

artist = 'karel gott'
track = 'eine liebe ist viele tranen wert'

if len(sys.argv) > 1:
    search_str = sys.argv[1]
else:
    search_str = 'artist:{} track:{}'.format(artist, track)

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
result = sp.search(q=search_str)
pprint.pprint(result)

Body:
By default the API will search through songs in the US market, that means songs that can legally only be listened by US customers.

I found that the song you are looking for is available in countries across Europe. For that song I get results in the GB as well as FR markets, and even more results in the german one.

So, just specify the market where you are using Spotify from:

sp.search(q=search_str, market="DE")

Unfortunately I am not aware of an easy way to search through all markets at once.


问:
unable to compare password using firebase admin sdk in python
I am using admin-SDK of firebase in python

I have created a new user using the following code

```<code>user = auth.create_user(
        email=email,
        email_verified=False,
        password=password,
        display_name=name,
        disabled=False)
</code>```

now I have created a function that takes name , _email id _ and password from the user and fetch user using it's email id and then checks if entered details are correct.

```<code>def check_user(self, name, email, password):  # fixme compare password
    user = auth.get_user_by_email(email)
    if user.display_name == name and user.email == email:# add password comparision
        print('successful login')
        return True
    else:
        print('username or password incorrect')
    return False
</code>```

I want to compare password entered with the password stored, but I am unable to compare as I can't access password, I can only access passwordHash using user.passwordHash and passwordSalt using user.passwordSalt.

is there any away I can find passwordHash or passwordSalt of password so I can compare the hashes.

答:
The usual flow when using Firebase Authentication is that your users sign in with client-side code that uses a Firebase SDK directly. So in that case,
Firebase itself would be performing the check whether the password is correct.

You can perform the check yourself, but you'll have to hash the plaintext password from the user in your code and then compare the stored and calculated hash values, essentially duplicating what Firebase already does. Firebase uses a modified version of scrypt to encrypt the passwords.

Body:
I am using admin-SDK of firebase in python

I have created a new user using the following code

user = auth.create_user(
        email=email,
        email_verified=False,
        password=password,
        display_name=name,
        disabled=False)

now I have created a function that takes name , _email id _ and password from the user and fetch user using it's email id and then checks if entered details are correct.

def check_user(self, name, email, password):  # fixme compare password
    user = auth.get_user_by_email(email)
    if user.display_name == name and user.email == email:# add password comparision
        print('successful login')
        return True
    else:
        print('username or password incorrect')
    return False

I want to compare password entered with the password stored, but I am unable to compare as I can't access password, I can only access passwordHash using user.passwordHash and passwordSalt using user.passwordSalt.

is there any away I can find passwordHash or passwordSalt of password so I can compare the hashes.