问:
Reading from flash that's not part of the application
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

```<code>    if (param) function_call();
</code>```

but it should also work for other cases such as

```<code>    for(int i = 0; i < param2; i++)
</code>```

define with pointer cast

```<code>#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))
</code>```

Which leads to (using -Os):

```<code>8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883
</code>```

const variable

```<code>const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);
</code>```

leading to

```<code>800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0
</code>```

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

答:
As proposed by @old_timer in a comment above, I favour this solution:

In the linker file, I put

```<code>    CONF_PARAM = _config_start + 0x0083;
</code>```

In my config.hpp, I put

```<code>    extern const bool CONF_PARAM;
</code>```

which then can easily be accessed in any source file

```<code>    if (CONF_PARAM)
</code>```

This basically fulfills all "nice"-definitions of mine, as far as I can see.

Body:
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

    if (param) function_call();

but it should also work for other cases such as

    for(int i = 0; i < param2; i++)

define with pointer cast

#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))

Which leads to (using -Os):

8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883

const variable

const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);

leading to

800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

Body:
As proposed by @old_timer in a comment above, I favour this solution:

In the linker file, I put

    CONF_PARAM = _config_start + 0x0083;

In my config.hpp, I put

    extern const bool CONF_PARAM;

which then can easily be accessed in any source file

    if (CONF_PARAM)

This basically fulfills all "nice"-definitions of mine, as far as I can see.


来源: stackexchange

问:
Telethon async function to tkinter button
I have the this async function below and basically I wanna place It into the command of a button using tkinter.

```<code>async def main():
    await client.send_message('username', 'message')

with client:
    client.loop.run_until_complete(main())
</code>```

In message I wanna put the variable cpf of my code, but I don't know exactly how should place It all together. I'm very new with python, so sorry for anything wrong...

The code above is how I'm trying to do it, but It's running the function just when I run the code, and not when I press the Button. I'm getting ValueError: The message cannot be empty unless a file is provided

```<code>from telethon import TelegramClient, events, sync
from tkinter import *

api_id = xxxxx
api_hash = 'xxxxxx'

client = TelegramClient('session_name', api_id, api_hash)
client.start()

root = Tk()

canvas = Canvas(root)
canvas.pack()

code_entry = Entry(canvas)
code_entry.pack()

async def main():
    cpf = code_entry.get()
    await client.send_message('ConsignadoBot', cpf)

with client:
    client.loop.run_until_complete(main)

search_btn = Button(canvas, text='Consultar', command=main)
search_btn.pack()

root.mainloop()
</code>```

答:
Your code produces a completely different error before producing the one you claim to have.

with client:
    client.loop.run_until_complete(main)
```

<p>This line fails, because in <code>loop.run_until_complete()</code>, "an <code>asyncio.Future</code>, a coroutine or an awaitable is required":</p>

```Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 558, in run_until_complete
    future = tasks.ensure_future(future, loop=self)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 619, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required
```

<p>The correct code would be:</p>

<pre class="lang-py prettyprint-override"><code>with client:
    client.loop.run_until_complete(main())
</code>```

Now, it will error with "empty message" because it's executing before the user enters anything.

This code:

root.mainloop()
```

<p>Is blocking. Telethon is an <code>asyncio</code> library, which means the event loop won't be running unless you do something else, which means Telethon won't be able to make any progress.</p>

<p>This can be solved by making it async:</p>

<pre class="lang-py prettyprint-override"><code>async def main(interval=0.05):
    try:
        while True:
            # We want to update the application but get back
            # to asyncio's event loop. For this we sleep a
            # short time so the event loop can run.
            #
            # https://www.reddit.com/r/Python/comments/33ecpl
            root.update()
            await asyncio.sleep(interval)
    except KeyboardInterrupt:
        pass
    except tkinter.TclError as e:
        if 'application has been destroyed' not in e.args[0]:
            raise
    finally:
        await client.disconnect()

client.loop.run_until_complete(main())
</code>```

For a more carefully designed async-friendly tkinter app, see Telethon's gui.py example.

ContentLicense: CC BY-SA 4.0

Body:
I have the this async function below and basically I wanna place It into the command of a button using tkinter.

async def main():
    await client.send_message('username', 'message')

with client:
    client.loop.run_until_complete(main())

In message I wanna put the variable cpf of my code, but I don't know exactly how should place It all together. I'm very new with python, so sorry for anything wrong...

The code above is how I'm trying to do it, but It's running the function just when I run the code, and not when I press the Button. I'm getting ValueError: The message cannot be empty unless a file is provided

from telethon import TelegramClient, events, sync
from tkinter import *

api_id = xxxxx
api_hash = 'xxxxxx'

client = TelegramClient('session_name', api_id, api_hash)
client.start()

root = Tk()

canvas = Canvas(root)
canvas.pack()

code_entry = Entry(canvas)
code_entry.pack()

async def main():
    cpf = code_entry.get()
    await client.send_message('ConsignadoBot', cpf)

with client:
    client.loop.run_until_complete(main)

search_btn = Button(canvas, text='Consultar', command=main)
search_btn.pack()

root.mainloop()

Body:
Your code produces a completely different error before producing the one you claim to have.

with client:
    client.loop.run_until_complete(main)

This line fails, because in loop.run_until_complete(), "an asyncio.Future, a coroutine or an awaitable is required":

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 558, in run_until_complete
    future = tasks.ensure_future(future, loop=self)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 619, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required

The correct code would be:

with client:
    client.loop.run_until_complete(main())

Now, it will error with "empty message" because it's executing before the user enters anything.

This code:

root.mainloop()

Is blocking. Telethon is an asyncio library, which means the event loop won't be running unless you do something else, which means Telethon won't be able to make any progress.

This can be solved by making it async:

async def main(interval=0.05):
    try:
        while True:
            # We want to update the application but get back
            # to asyncio's event loop. For this we sleep a
            # short time so the event loop can run.
            #
            # https://www.reddit.com/r/Python/comments/33ecpl
            root.update()
            await asyncio.sleep(interval)
    except KeyboardInterrupt:
        pass
    except tkinter.TclError as e:
        if 'application has been destroyed' not in e.args[0]:
            raise
    finally:
        await client.disconnect()

client.loop.run_until_complete(main())

For a more carefully designed async-friendly tkinter app, see Telethon's gui.py example.


问:
Unable to load local website inside Iframe in Edge
I've two sites site-1 (Parent) and site-2 (child). Both are hosted on two machines on IIS V10 (windows 10) on the same network. Site-2 is loaded inside site-1 using Iframe.

The site-2 is loaded in Iframe in all browsers (Chrome, Firefox, IE) but Edge. I get following error in Edge:

Here, I am using IP address and port for the site-2 in the iframe instead of the hostname.

Here is how I am creating Iframe in JS:

```<code>var elem = document.createElement("iframe");
elem.setAttribute("src", "http://172.18.48.43:5051/play/Web/21");
elem.setAttribute("id", "site-2");
elem.style.width = 800 + "px";
elem.style.height = 300 + "px";
elem.style.border = 1 + "px solid Orange";
var frame = document.getElementById('frame');
$("#frame").html(elem);
</code>```

The Iframe works in edge in two conditions:

If both site-1 and site-2 are on the same machine.

If instead of IP, I use public domain hostname like http://www.some-domain.com

I tried following solutions, but nothing worked so far:

https://windowsreport.com/fix-hmm-we-cant-reach-this-page-edge/

https://troubleshooter.xyz/wiki/fix-hmm-we-cant-reach-this-page-error-in-microsoft-edge/

Why does Microsoft Edge open some local websites, but not others, where the domain name is routed to 127.0.0.1 in hosts file

答: I have similar issue. You can try loading the iframe child-app (site 2) in another tab and refresh to see if the iframe will load accordingly. That works for us.</p>

Body:
I've two sites site-1 (Parent) and site-2 (child). Both are hosted on two machines on IIS V10 (windows 10) on the same network. Site-2 is loaded inside site-1 using Iframe.

The site-2 is loaded in Iframe in all browsers (Chrome, Firefox, IE) but Edge. I get following error in Edge:

Here, I am using IP address and port for the site-2 in the iframe instead of the hostname.

Here is how I am creating Iframe in JS:

var elem = document.createElement("iframe");
elem.setAttribute("src", "http://172.18.48.43:5051/play/Web/21");
elem.setAttribute("id", "site-2");
elem.style.width = 800 + "px";
elem.style.height = 300 + "px";
elem.style.border = 1 + "px solid Orange";
var frame = document.getElementById('frame');
$("#frame").html(elem);

The Iframe works in edge in two conditions:

If both site-1 and site-2 are on the same machine.

If instead of IP, I use public domain hostname like http://www.some-domain.com

I tried following solutions, but nothing worked so far:

https://windowsreport.com/fix-hmm-we-cant-reach-this-page-edge/

https://troubleshooter.xyz/wiki/fix-hmm-we-cant-reach-this-page-error-in-microsoft-edge/

Why does Microsoft Edge open some local websites, but not others, where the domain name is routed to 127.0.0.1 in hosts file


问:
CSS not affecting bootstrap navbar background color
I'm trying to set a new color for a bootstrap navbar component but having trouble. Does it have to do with failure to override bootstrap or css link placement? I've tried omitting the bootstrap bg-light setting and defining the navbar background color in main.css as well. What am I missing? Here is the HTML of interest:

```<code>{% extends 'bootstrap/base.html' %}

{% block title %}Welcome{% endblock title %}

{% block html_attribs %}lang='en'{% endblock html_attribs %}

{% block head %}
<head>
    <!-- Required meta tags -->
    {% block meta %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    {% endblock meta %}

    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type='text/css' href="{{ url_for('static', filename='main.css' )}}">

    <title>Welcome</title>

    {% block navbar %}
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav">
            <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            <a class="nav-item nav-link" href="#">About</a>
            <a class="nav-item nav-link" href="#">Register</a>
            <a class="nav-item nav-link disabled" href="#">Login</a>
          </div>
        </div>
      </nav>
    {% endblock navbar %}
  </head>
{% endblock head %}

{% block body %}
<body>
    <h1></h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
{% endblock body %}

{% block scripts %}
{{ super() }}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
{% endblock scripts %}
</code>```

And here is the "main.css" file:

```<code>body {
    background: #F9DCC4;
    color: #333333;
  }

  .navbar-expand-lg {
    background-color: rgb(150, 144, 143);
  }
</code>```

Thanks!

答:
Your CSS rule is most probably being overridden by Bootstrap. Try use the !important property, like bellow, or change the order you import your stylesheets.

```<code>.navbar-expand-lg {
    background-color: rgb(150, 144, 143) !important;
}
</code>```

Body:
I'm trying to set a new color for a bootstrap navbar component but having trouble. Does it have to do with failure to override bootstrap or css link placement? I've tried omitting the bootstrap bg-light setting and defining the navbar background color in main.css as well. What am I missing? Here is the HTML of interest:

{% extends 'bootstrap/base.html' %}

{% block title %}Welcome{% endblock title %}

{% block html_attribs %}lang='en'{% endblock html_attribs %}

{% block head %}

    {% block meta %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    {% endblock meta %}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type='text/css' href="{{ url_for('static', filename='main.css' )}}">

    <title>Welcome</title>

    {% block navbar %}

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            Home (current)
            About
            Register
            Login

    {% endblock navbar %}

{% endblock head %}

{% block body %}

{% endblock body %}

{% block scripts %}
{{ super() }}

{% endblock scripts %}

And here is the "main.css" file:

body {
    background: #F9DCC4;
    color: #333333;
  }

  .navbar-expand-lg {
    background-color: rgb(150, 144, 143);
  }

Thanks!

Body:
Your CSS rule is most probably being overridden by Bootstrap. Try use the !important property, like bellow, or change the order you import your stylesheets.

.navbar-expand-lg {
    background-color: rgb(150, 144, 143) !important;
}


问:
Selectable panel in Swing
I´m trying to make something similar to the downloads panel of Transmission BT (here an image: http://www.transmissionbt.com/images/screenshots/Mac-Large.jpg) but I´m having some problems.
I made a JPanel with the progress bar, labels, icon and buttons and then added this panel to a container (JPanel again) but I need to make this component selectable.

How can I do this?

答: You can simply use JList and ListCellRenderer to render your existing panel in a JList .

ContentLicense: CC BY-SA 3.0

Title: Selectable panel in Swing


问:
Can't change nav-link color in bootstrap 4
```<code><nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
        <div class="mx-auto my-2 order-0 order-md-1 position-relative">
            <div id="top_logo" class="container-fluid">
                <span>VirtualQR</span>
            </div>
        </div>
        <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#section_navbar">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_pricing">Pricings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_contact">Contacts</a>
                </li>
            </ul>
</code>```

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

答:
What you can do is this:</p>

```<code>.nav-link{
  color:red;
}
</code>```

Body:
                VirtualQR

                    Home

                    How does it work?

                    Pricings

                    Contacts

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

Body:
What you can do is this:

.nav-link{
  color:red;
}


问:
asp.net core 2.1 odata use different name of entity in the route
I have a long name of of entity in my code EmployeTraining which used as entity in OData and with same name for the controller.

```<code>Startup.cs

 app.UseMvc(routeBuilder=>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
            routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1", EdmModelBuilder.GetEdmModelEmploye());

        });

EdmModelBuilder.cs

public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("EmployeTraining");
        return builder.GetEdmModel();
    }

EmployeTrainingControllers.cs

public class EmployeTrainingController : ODataController
{
    internal IEmployeService ServiceEmploye { get; set; }

    public EmployesController(IEmployeService serviceEmploye)
    {

        ServiceEmploye = serviceEmploye;
    }

    //// GET api/employes
    [HttpGet]
    [MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

        return ServiceEmploye.GetListeEmployes();
    }
}
</code>```

To call my service it works only through this URL: https://{server}/odata/v1/rh/employetraining

but I need to  use this https://{server}/odata/v1/rh/employe-training
any help please.

答:
For such scenario,change like below:

1.Change the entityset name:

```<code>public static class EdmModelBuilder
{
    public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("employe-training");
        return builder.GetEdmModel();
    }
}
</code>```

2.Add the attribute:

```<code>public class EmployeTrainingController : ODataController
{
    [HttpGet]
    [ODataRoute("employe-training")]
    //[MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

         return ServiceEmploye.GetListeEmployes();
    }
}
</code>```

3.Startup.cs:

```<code>app.UseMvc(routeBuilder=>
{
     routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
     routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1/rh", EdmModelBuilder.GetEdmModelEmploye());

});
</code>```

Request the url:https://{server}/odata/v1/rh/employe-training

Body:
I have a long name of of entity in my code EmployeTraining which used as entity in OData and with same name for the controller.

Startup.cs

 app.UseMvc(routeBuilder=>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
            routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1", EdmModelBuilder.GetEdmModelEmploye());

        });

EdmModelBuilder.cs

public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("EmployeTraining");
        return builder.GetEdmModel();
    }

EmployeTrainingControllers.cs

public class EmployeTrainingController : ODataController
{
    internal IEmployeService ServiceEmploye { get; set; }

    public EmployesController(IEmployeService serviceEmploye)
    {

        ServiceEmploye = serviceEmploye;
    }

    //// GET api/employes
    [HttpGet]
    [MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

        return ServiceEmploye.GetListeEmployes();
    }
}

To call my service it works only through this URL: https://{server}/odata/v1/rh/employetraining

but I need to  use this https://{server}/odata/v1/rh/employe-training
any help please.

Body:
For such scenario,change like below:

1.Change the entityset name:

public static class EdmModelBuilder
{
    public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("employe-training");
        return builder.GetEdmModel();
    }
}

2.Add the attribute:

public class EmployeTrainingController : ODataController
{
    [HttpGet]
    [ODataRoute("employe-training")]
    //[MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

         return ServiceEmploye.GetListeEmployes();
    }
}

3.Startup.cs:

app.UseMvc(routeBuilder=>
{
     routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
     routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1/rh", EdmModelBuilder.GetEdmModelEmploye());

});

Request the url:https://{server}/odata/v1/rh/employe-training


问:
JPA - OneToMany with OR condition
I have 2 SQL tables, "node" and "edge".

The "node" table has a composite primary key, which consists of two columns: "id" and "type".

The "edge" table contains the following columns:

node_1_id: the id of the first node of the edge

node_1_type: the type of the first node of the edge

node_2_id: the id of the second node of the edge

node_2_type: the type of the second node of the edge

There are also two foreign key constraints that link ("node_1_id", "node_1_type") and ("node_2_id", "node_2_type") to the "id" and "type" of the "node" table.

I've created the following jpa entity:

```<code>@Entity
@Table(name = "edge")
public class Edge {
    @Id
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "description", nullable = true, length = 100)
    private String description;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "node_1_id", referencedColumnName = "id"),
        @JoinColumn(name = "node_1_type", referencedColumnName = "type")
    })
    private Node node1;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "node_2_id", referencedColumnName = "id"),
        @JoinColumn(name = "node_2_type", referencedColumnName = "type")
    })
    private Node node2;
}
</code>```

In "Node" entity I would like to create a "OneToMany" relation called "edges" that fetches all the edges linked to a node (it doesn't matter if it is the first or the second node).

This is the correspondent SQL query:

```<code>select *
from node n join edge e
on (n.id = e.node_1_id and n.type = e.node_1_type) or (n.id = e.node_2_id and n.type = e.node_2_type)
where n.id = 1 and n.type = 'type';
</code>```

How can I create such relation?

答:
Is it mandatory to be a single @OneToMany relationship? Otherwise you could add the counterparts to the two @ManyToOne relationships and create a getter that simply returns a single, merged list:

```<code>public class Node {

    @OneToMany(mappedBy="node1")
    private List<Edge> firstNodeEdges;

    @OneToMany(mappedBy="node2")
    private List<Edge> secondNodeEdges;

    public List<Edge> getEdges() {
        return Stream.concat(firstNodeEdges.stream(), secondNodeEdges.stream())
            .collect(Collectors.toList());
    }
}
</code>```

Title: JPA - OneToMany with OR condition

Body:
I have 2 SQL tables, "node" and "edge".

The "node" table has a composite primary key, which consists of two columns: "id" and "type".

The "edge" table contains the following columns:

node_1_id: the id of the first node of the edge

node_1_type: the type of the first node of the edge

node_2_id: the id of the second node of the edge

node_2_type: the type of the second node of the edge

There are also two foreign key constraints that link ("node_1_id", "node_1_type") and ("node_2_id", "node_2_type") to the "id" and "type" of the "node" table.

I've created the following jpa entity:

@Entity
@Table(name = "edge")
public class Edge {
    @Id
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "description", nullable = true, length = 100)
    private String description;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "node_1_id", referencedColumnName = "id"),
        @JoinColumn(name = "node_1_type", referencedColumnName = "type")
    })
    private Node node1;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "node_2_id", referencedColumnName = "id"),
        @JoinColumn(name = "node_2_type", referencedColumnName = "type")
    })
    private Node node2;
}

In "Node" entity I would like to create a "OneToMany" relation called "edges" that fetches all the edges linked to a node (it doesn't matter if it is the first or the second node).

This is the correspondent SQL query:

select *
from node n join edge e
on (n.id = e.node_1_id and n.type = e.node_1_type) or (n.id = e.node_2_id and n.type = e.node_2_type)
where n.id = 1 and n.type = 'type';

How can I create such relation?

Body:
Is it mandatory to be a single @OneToMany relationship? Otherwise you could add the counterparts to the two @ManyToOne relationships and create a getter that simply returns a single, merged list:

public class Node {

    @OneToMany(mappedBy="node1")
    private List<Edge> firstNodeEdges;

    @OneToMany(mappedBy="node2")
    private List<Edge> secondNodeEdges;

    public List<Edge> getEdges() {
        return Stream.concat(firstNodeEdges.stream(), secondNodeEdges.stream())
            .collect(Collectors.toList());
    }
}


问:
Generating large DataFrame in a distributed way in pyspark efficiently (without pyspark.sql.Row)
The problem boils down to the following: I want to generate a DataFrame in pyspark using existing parallelized collection of inputs and a function which given one input can generate a relatively large batch of rows. In the example below I want to generate 10^12 rows dataframe using e.g. 1000 executors:

```<code>def generate_data(one_integer):
  import numpy as np
  from pyspark.sql import Row
  M = 10000000 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  row_type = Row("seed", "n", "x")
  return [row_type(one_integer, i, float(np_array[i])) for i in range(M)]

N = 100000 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = spark.sparkContext.parallelize(list_of_integers)
row_rdd = list_of_integers_rdd.flatMap(list_of_integers_rdd)
from pyspark.sql.types import StructType, StructField, FloatType, IntegerType
my_schema = StructType([
       StructField("seed", IntegerType()),
       StructField("n", IntegerType()),
       StructField("x", FloatType())])
df = spark.createDataFrame(row_rdd, schema=my_schema)
</code>```

(I don't really want to study distribution of random numbers given seed - this is just an example I was able to come up with to illustrate the situation when large dataframe is not loaded from warehouse, but generated by the code)

The code above does pretty much exactly what I want. Problem is that it does it in a very inefficient way - at expense of creating a python Row object for each row, then converting the python Row objects into internal Spark columnar representation.

Is there a way I can convert batch of rows already in columnar representation (e.g. one or a few numpy arrays as above np_array) just by letting spark know that these are the columns of a batch of values?

E.g. I can write the code to generate python collection RDD where each element is an pyarrow.RecordBatch or a pandas.DataFrame, but I can't find a way to convert any of these into Spark DataFrame without creating an RDD of pyspark Row objects in the process.

There is at least a dozen of articles with examples how I can use pyarrow + pandas to convert a local (to driver) pandas dataframe to Spark dataframe efficiently, but that is not an option for me because I need data to be actually generated in a distributed way on executors rather than generating one pandas dataframe on driver and sending that to executors.

UPD.
I've found one way to avoid creation of Row objects - using RDD of python tuples. As expected it is still way too slow, but still a bit faster than using Row objects. Still, this is not really what I'm looking for (which is a really efficient way of passing columnar data to Spark from python).

Also measured time to do certain operations on a machine (crude way with quite a bit of variation in measured time, but still it representative in my opinion):
The dataset in question is 10M rows, 3 cols (one column is constant integer, other is integer range from 0 to 10M-1, third is floating point value generated using np.random.random_sample:

Locally generate pandas dataframe (10M rows): ~440-450ms

Locally generate python list of spark.sql.Row objects (10M rows): ~12-15s

Locally generate python list of tuples representing rows (10M rows): ~3.4-3.5s

Generate Spark dataframe using just 1 executor and 1 initial seed value:

using spark.createDataFrame(row_rdd, schema=my_schema): ~70-80s

using spark.createDataFrame(tuple_rdd, schema=my_schema): ~40-45s

(non-distributed creation) using spark.createDataFrame(pandas_df, schema=my_schema): ~0.4-0.5s (without pandas df generation itself which takes roughly same time) - with spark.sql.execution.arrow.enabled set to true.

The example with local-to-driver pandas dataframe converted to Spark dataframe in ~1s for 10M rows gives me a reason to believe same should be possible with dataframes generated in executors. However fastest I can achieve now is ~40s for 10M rows using RDD of python tuples.

So the question still stays - is there a way to generate a large Spark dataframe in a distributed way efficiently in pyspark?

答:
here is a solution that is not using RDD or creating Rows, but only with dataframe operation:

(code is in scala, but doing the same in python should be simple)

```<code>val N = 100000

//for seed return array of index and random_value
def generate_data(i: Int): Array[(Int, Double)] = ???
val generate_data_udf = udf (generate_data _)

spark
  .range(N)
  .toDF("seed")
  .withColumn("arr", generate_data_udf($"seed"))
  .select(
    $"seed",
    explode($"arr") as "exp"
  )
  .select(
    $"seed",
    $"exp._1" as "n",
    $"exp._2" as "x"
  )
</code>```

Body:
The problem boils down to the following: I want to generate a DataFrame in pyspark using existing parallelized collection of inputs and a function which given one input can generate a relatively large batch of rows. In the example below I want to generate 10^12 rows dataframe using e.g. 1000 executors:

def generate_data(one_integer):
  import numpy as np
  from pyspark.sql import Row
  M = 10000000 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  row_type = Row("seed", "n", "x")
  return [row_type(one_integer, i, float(np_array[i])) for i in range(M)]

N = 100000 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = spark.sparkContext.parallelize(list_of_integers)
row_rdd = list_of_integers_rdd.flatMap(list_of_integers_rdd)
from pyspark.sql.types import StructType, StructField, FloatType, IntegerType
my_schema = StructType([
       StructField("seed", IntegerType()),
       StructField("n", IntegerType()),
       StructField("x", FloatType())])
df = spark.createDataFrame(row_rdd, schema=my_schema)

(I don't really want to study distribution of random numbers given seed - this is just an example I was able to come up with to illustrate the situation when large dataframe is not loaded from warehouse, but generated by the code)

The code above does pretty much exactly what I want. Problem is that it does it in a very inefficient way - at expense of creating a python Row object for each row, then converting the python Row objects into internal Spark columnar representation.

Is there a way I can convert batch of rows already in columnar representation (e.g. one or a few numpy arrays as above np_array) just by letting spark know that these are the columns of a batch of values?

E.g. I can write the code to generate python collection RDD where each element is an pyarrow.RecordBatch or a pandas.DataFrame, but I can't find a way to convert any of these into Spark DataFrame without creating an RDD of pyspark Row objects in the process.

There is at least a dozen of articles with examples how I can use pyarrow + pandas to convert a local (to driver) pandas dataframe to Spark dataframe efficiently, but that is not an option for me because I need data to be actually generated in a distributed way on executors rather than generating one pandas dataframe on driver and sending that to executors.

UPD.
I've found one way to avoid creation of Row objects - using RDD of python tuples. As expected it is still way too slow, but still a bit faster than using Row objects. Still, this is not really what I'm looking for (which is a really efficient way of passing columnar data to Spark from python).

Also measured time to do certain operations on a machine (crude way with quite a bit of variation in measured time, but still it representative in my opinion):
The dataset in question is 10M rows, 3 cols (one column is constant integer, other is integer range from 0 to 10M-1, third is floating point value generated using np.random.random_sample:

Locally generate pandas dataframe (10M rows): ~440-450ms

Locally generate python list of spark.sql.Row objects (10M rows): ~12-15s

Locally generate python list of tuples representing rows (10M rows): ~3.4-3.5s

Generate Spark dataframe using just 1 executor and 1 initial seed value:

using spark.createDataFrame(row_rdd, schema=my_schema): ~70-80s

using spark.createDataFrame(tuple_rdd, schema=my_schema): ~40-45s

(non-distributed creation) using spark.createDataFrame(pandas_df, schema=my_schema): ~0.4-0.5s (without pandas df generation itself which takes roughly same time) - with spark.sql.execution.arrow.enabled set to true.

The example with local-to-driver pandas dataframe converted to Spark dataframe in ~1s for 10M rows gives me a reason to believe same should be possible with dataframes generated in executors. However fastest I can achieve now is ~40s for 10M rows using RDD of python tuples.

So the question still stays - is there a way to generate a large Spark dataframe in a distributed way efficiently in pyspark?

Body:
here is a solution that is not using RDD or creating Rows, but only with dataframe operation:

(code is in scala, but doing the same in python should be simple)

val N = 100000

//for seed return array of index and random_value
def generate_data(i: Int): Array[(Int, Double)] = ???
val generate_data_udf = udf (generate_data _)

spark
  .range(N)
  .toDF("seed")
  .withColumn("arr", generate_data_udf($"seed"))
  .select(
    $"seed",
    explode($"arr") as "exp"
  )
  .select(
    $"seed",
    $"exp._1" as "n",
    $"exp._2" as "x"
  )


问:
Python multithreading pyshark
Im new to python and I'm testing the library pyshark.

I want to sniff the traffic all the time and do other things. But when I start the sniffer, all other code stop working. I've tried asyincio thread and multithreading, but it always give me different errors.

This the code that I want to run without blocking the application.

```<code>import pyshark
import asyncio

class Sniffer:

    @staticmethod
    @asyncio.coroutine
    def sniff():
        cap = pyshark.LiveCapture(interface='en0')
        cap.sniff_continuously(packet_count=0)
        for pkt in cap:
            print(pkt)
</code>```

Thanks in advice.

答:
You can try multi-threading class.
https://docs.python.org/3/library/threading.html

For example :

```<code>import thread
obj = Sniffer()
thread.start_new_thread( obj.sniff,)
</code>```

Another way if you tired to multi threading or someone else, create new python file and import your sniffer.

For example :

```<code># new python file
import sniffer
obj = sniffer.Sniffer()
while True:
    obj.sniff()
</code>```

Thi way use your processor cores. This is as multi thread with little difference, your operating system make this work automatically.

Title: Python multithreading pyshark

Body:
Im new to python and I'm testing the library pyshark.

I want to sniff the traffic all the time and do other things. But when I start the sniffer, all other code stop working. I've tried asyincio thread and multithreading, but it always give me different errors.

This the code that I want to run without blocking the application.

import pyshark
import asyncio

class Sniffer:

    @staticmethod
    @asyncio.coroutine
    def sniff():
        cap = pyshark.LiveCapture(interface='en0')
        cap.sniff_continuously(packet_count=0)
        for pkt in cap:
            print(pkt)

Thanks in advice.

Body:
You can try multi-threading class.
https://docs.python.org/3/library/threading.html

For example :

import thread
obj = Sniffer()
thread.start_new_thread( obj.sniff,)

Another way if you tired to multi threading or someone else, create new python file and import your sniffer.

For example :

# new python file
import sniffer
obj = sniffer.Sniffer()
while True:
    obj.sniff()

Thi way use your processor cores. This is as multi thread with little difference, your operating system make this work automatically.


问:
Get some set of values in SQL Server
I have a query, in this query I need to get a number of classes (class count) in each district. In here it comes only those who have classes. So I need to show the district's it doesn't have a classes as well.

My District table consist 25 values. and my class coverage table has 5 values to 3 districts. I need to show all the districts.

Code

```<code>SELECT
    CC.DistrictId, D.DistrictName,
    COUNT(D.DistrictId) AS DistrictCount
FROM
    TBL_T_ClassCoverage CC
LEFT JOIN
    [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE
    CC.IsActive = 1
GROUP BY
    CC.DistrictId, D.DistrictName
ORDER BY
    DistrictId ASC
</code>```

答:
You need to join your tables the other way, from districts to classes, to ensure that all district values are in the output:</p>

```<code>  SELECT D.DistrictId, D.DistrictName, COUNT(CC.DistrictId) AS DistrictCount
  FROM [dbo].[TBL_M_District] D
  LEFT JOIN TBL_T_ClassCoverage CC
  ON CC.DistrictId = D.DistrictId AND CC.IsActive = 1
  GROUP BY D.DistrictId, D.DistrictName
  ORDER BY D.DistrictId ASC
</code>```

Title: Get some set of values in SQL Server

Body:
I have a query, in this query I need to get a number of classes (class count) in each district. In here it comes only those who have classes. So I need to show the district's it doesn't have a classes as well.

My District table consist 25 values. and my class coverage table has 5 values to 3 districts. I need to show all the districts.

Code

SELECT
    CC.DistrictId, D.DistrictName,
    COUNT(D.DistrictId) AS DistrictCount
FROM
    TBL_T_ClassCoverage CC
LEFT JOIN
    [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE
    CC.IsActive = 1
GROUP BY
    CC.DistrictId, D.DistrictName
ORDER BY
    DistrictId ASC

Body:
You need to join your tables the other way, from districts to classes, to ensure that all district values are in the output:

  SELECT D.DistrictId, D.DistrictName, COUNT(CC.DistrictId) AS DistrictCount
  FROM [dbo].[TBL_M_District] D
  LEFT JOIN TBL_T_ClassCoverage CC
  ON CC.DistrictId = D.DistrictId AND CC.IsActive = 1
  GROUP BY D.DistrictId, D.DistrictName
  ORDER BY D.DistrictId ASC


问:
I need to gather review statistics from GitHub on our project
I need to extract information from our private GitHub repo regarding the number of reviews each of our collaborators are doing during a set time period.

I've been reviewing the GitHub documentation but it's not obvious to me if it's even possible using their REST API.

I want to use the data to present the information in  a graph online automatically, so REST is the prefered way.

Does anyone know if it's even possible?

Thanks,
/J

答:
the best way is to use the GitHub API v4 (graphql) endpoints. The PullRequests object reviews attribute will let you get all the reviews for a repository PRs (the reviews attribute). You'll need to fetch the list of your repositories using the repositories attribute. The graphql API is more efficient than the rest API (v3).

Depending of the size of your repositories the crawler could be complex to build because you'll be face of any kind of corner cases such as network issues, API slowness, ...

I'm working on a project called monocle that gather repositories statistics about Pull Request on GitHub. Various metrics will be shown is form of graphs or lists. For instance you'll see the amount of reviews and/or comments done by someone to someone else. The tool also display a chord graph with the review strength between peers (see the attached picture).

Here is the project's GitHub page and a link to the demo node where various GitHub orgs are indexed here Ansible.

The tool is quite easy to deploy using docker compose.


问:
Continue in while inside foreach
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}
</code>```

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

答:
The break; keyword will exit a loop:

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        if (this.MoveToNextObject())
        {
            break;
        }
        this.boolValue = this.ResumeWhileLoop();
    }
}
</code>```

OwnerDisplayName: Amr

ContentLicense: CC BY-SA 2.5

Title: Continue in while inside foreach

Body:
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

LastEditorDisplayName: configurator

Body:
The break; keyword will exit a loop:

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        if (this.MoveToNextObject())
        {
            break;
        }
        this.boolValue = this.ResumeWhileLoop();
    }
}

OwnerDisplayName: Mitch Wheat


问:
Android: Disable text selection in a webview
I am using a webview to present some formatted stuff in my app. For some interaction (which are specific to certain dom elements) I use javascript and WebView.addJavascriptInterface(). Now, I want to recognize a long touch. Unfortunately, onLongTouch, in Android 2.3 the handles for text selection are displayed.

How can I turn off this text selection without setting the onTouchListener and return true? (Then, the interaction with the "website" doesn't work anymore.

答:
For kotlin i found the following to work:</p>

```<code>webView.isLongClickable = false
</code>```

Body:
For kotlin i found the following to work:

webView.isLongClickable = false


问:
Trying to plot a graph using a list of column names using seaborn
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

```<code>fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
</code>```

Output plot

答:
Try replacing the following line of code:

```<code>ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
</code>```

with the following:

```<code>ax[i,j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
</code>```

Body:
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')

Output plot

Body:
Try replacing the following line of code:

ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')

with the following:

ax[i,j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')


问:
How to determine if one offset contained with another offset area?
I would like to determine if a widget is touching another widget, so far I have the following offset - Positions of widgets. However, this is a single point rather the a contained area.

Offset(48.8, 425.6) <- Box 1
Offset(70.0, 456.0) <-- Box 2

What is the best way to determine if Box 1 is near box 2 ( Box 2 would be scaled out by xx number to improve the matching )

I am using GlobalKeys to determine position like below

```<code>RenderBox box1 = box1Key.currentContext.findRenderObject();
Offset box1Pos = box1.localToGlobal(Offset.zero);

RenderBox box2 = box2Key.currentContext.findRenderObject();
Offset box2Pos = box2.localToGlobal(Offset.zero);
</code>```

答:
You could use the class Rect to define the boundings of one of your widgets and then use the method contains

https://api.flutter.dev/flutter/dart-ui/Rect/contains.html

The Rect class also has the method intersect which can be better suited for your question.

https://api.flutter.dev/flutter/dart-ui/Rect/intersect.html

Body:
I would like to determine if a widget is touching another widget, so far I have the following offset - Positions of widgets. However, this is a single point rather the a contained area.

Offset(48.8, 425.6) <- Box 1
Offset(70.0, 456.0) <-- Box 2

What is the best way to determine if Box 1 is near box 2 ( Box 2 would be scaled out by xx number to improve the matching )

I am using GlobalKeys to determine position like below

RenderBox box1 = box1Key.currentContext.findRenderObject();
Offset box1Pos = box1.localToGlobal(Offset.zero);

RenderBox box2 = box2Key.currentContext.findRenderObject();
Offset box2Pos = box2.localToGlobal(Offset.zero);


问:
Defined Edges With CSS3 Filter Blur
I am blurring some images with this code

```<code>img {
  filter: blur(5px);
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
}
</code>```

The edges of the image get blurred too though. Is it possible to blur the image, while keeping the edges defined? Like an inset blur or something?

答:
The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:

CSS:

```<code>div{
margin: 2rem;
height: 100vh;
overflow: hidden;
display: inline-block;
border: 1px solid #00000000;
}

img {
-webkit-filter: blur(2rem);
filter: blur(2rem);
}
</code>```

HTML

```<code><div><img src='https://images.unsplash.com/photo-1557853197-aefb550b6fdc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=375&q=80' /></div>
</code>```

Here's a codepen depicting the same:
https://codepen.io/arnavozil/pen/ExPYKNZ

Title: Defined Edges With CSS3 Filter Blur

Body:
I am blurring some images with this code

img {
  filter: blur(5px);
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
}

The edges of the image get blurred too though. Is it possible to blur the image, while keeping the edges defined? Like an inset blur or something?

Body:
The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:

CSS:

div{
margin: 2rem;
height: 100vh;
overflow: hidden;
display: inline-block;
border: 1px solid #00000000;
}

img {
-webkit-filter: blur(2rem);
filter: blur(2rem);
}

HTML

<div><img src='https://images.unsplash.com/photo-1557853197-aefb550b6fdc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=375&q=80' /></div>

Here's a codepen depicting the same:
https://codepen.io/arnavozil/pen/ExPYKNZ


问:
Pipe Events from Azure Event Hub to Azure Service Bus
I am listening to Event hub for various events.

Each event is high value and cannot be missed.

Events are partitioned based on device id.

Events from one device id are sparse and not very frequent (couple of events per few dasy) . It only occurs in response to a user action which is infrequent.

The number of devices are huge , so I will have a lot of events for a variety of device Ids.

For each event , I need to make 3-4 API calls to Systems which are not super reliable. And since some of these are cross Geo Calls it might take some time.

I am planning to take the events from Event hub and put them into Service Bus. My reasons are as follows.

Event hub can be scaled to only 32 partitions and if one event takes time , the entire partition gets blocked.

Service bus on the other hand is more horizontally scalable. If the throughput drops I can just add more subscribers to the Service Bus.

I have been looking for patterns like this but I have not seen patterns where we get data from a log based messaging system and push them to a queue based one.

Are there better approach to handle such scenarios ?

答:
I think you can use Event hub trigger and service bus output binding to achieve what you want.

For example, I want to monitor Event hub 'test' and I am using C# library:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace FunctionApp68
{
    public static class Function1
    {
        [FunctionName("Function1")]
        [return: ServiceBus("test1", Connection = "ServiceBusConnection")]
        public static string Run([EventHubTrigger("test", Connection = "str")] EventData[] events, ILogger log)
        {
            var exceptions = new List<Exception>();
            string messageBodyt = "";
            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
                    messageBodyt = messageBodyt + messageBody;
                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    //await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
                throw new AggregateException(exceptions);

            if (exceptions.Count == 1)
                throw exceptions.Single();
            return messageBodyt;
        }
    }
}
</code>```

The above code will collect from event hub 'test' and save to service bus queue 'test1'.

Have a look of these doc:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=csharp

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-output?tabs=csharp#example

Body:
I think you can use Event hub trigger and service bus output binding to achieve what you want.

For example, I want to monitor Event hub 'test' and I am using C# library:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace FunctionApp68
{
    public static class Function1
    {
        [FunctionName("Function1")]
        [return: ServiceBus("test1", Connection = "ServiceBusConnection")]
        public static string Run([EventHubTrigger("test", Connection = "str")] EventData[] events, ILogger log)
        {
            var exceptions = new List<Exception>();
            string messageBodyt = "";
            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
                    messageBodyt = messageBodyt + messageBody;
                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    //await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
                throw new AggregateException(exceptions);

            if (exceptions.Count == 1)
                throw exceptions.Single();
            return messageBodyt;
        }
    }
}

The above code will collect from event hub 'test' and save to service bus queue 'test1'.

Have a look of these doc:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=csharp

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-output?tabs=csharp#example


问:
How to pass a docker variable to jboss-cli.sh?
I have a variable in my jboss cli file, let's call it ${FOO}.

I can see that the variable is set in my Dockerfile, if I:

```<code>RUN echo ${FOO}
</code>```

I see the value printed.

I have a foo.cli file which contains a line similar to:

```<code>/system-property=foo:add(value="${FOO}")
</code>```

and when I run jboss-cli.sh foo.cli

I get:

```<code>Cannot resolve expression ${FOO}.
</code>```

Is there a way to pass a variable from Docker to the file argument to jboss-cli.sh ?

I've tried removing the quotes around ${FOO} also in the system-property line but no luck.

答:
This is due to the fact that the CLI does not treat values the same as names. In short, operation names, parameter names, header names and values, command names as well as command argument names are resolved automatically. Parameter and argument values aren’t. To fix this, we need to set resolve-parameter-values to true in jboss-cli.xml.

For e.g.:-

```<code>sed -i "s/<resolve-parameter-values>false<\/resolve-parameter-values>/\
<resolve-parameter-values>true<\/resolve-parameter-values>/" \
$JBOSS_HOME/bin/jboss-cli.xml
</code>```

Note that the command above is meant to be a one-off solution. From the maintenance perspective, using sed for XML is not a good idea in general. If you’re automating this, consider using XPath instead.

Note:- This functionality requires WildFly 8.0.0.CR1 or newer.

Body:
I have a variable in my jboss cli file, let's call it ${FOO}.

I can see that the variable is set in my Dockerfile, if I:

RUN echo ${FOO}

I see the value printed.

I have a foo.cli file which contains a line similar to:

/system-property=foo:add(value="${FOO}")

and when I run jboss-cli.sh foo.cli

I get:

Cannot resolve expression ${FOO}.

Is there a way to pass a variable from Docker to the file argument to jboss-cli.sh ?

I've tried removing the quotes around ${FOO} also in the system-property line but no luck.

Body:
This is due to the fact that the CLI does not treat values the same as names. In short, operation names, parameter names, header names and values, command names as well as command argument names are resolved automatically. Parameter and argument values aren’t. To fix this, we need to set resolve-parameter-values to true in jboss-cli.xml.

For e.g.:-

sed -i "s/<resolve-parameter-values>false<\/resolve-parameter-values>/\
<resolve-parameter-values>true<\/resolve-parameter-values>/" \
$JBOSS_HOME/bin/jboss-cli.xml

Note that the command above is meant to be a one-off solution. From the maintenance perspective, using sed for XML is not a good idea in general. If you’re automating this, consider using XPath instead.

Note:- This functionality requires WildFly 8.0.0.CR1 or newer.


问:
Failed to compile. ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src'
I have this error Failed to compile.  ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src' but I have installed it

and this is my main.js

```<code>import Vue from 'vue';
import App from './App.vue';
import vuetify from '.plugins/vuetify';

Vue.config.productionTip = false;

new Vue({
 vuetify,
 render: (h) => h(App),
}).$mount('#app');
</code>```

答:
Use

```<code>import vuetify from './plugins/vuetify'
</code>```

Notice the slightest of path difference before plugins here

Body:
I have this error Failed to compile.  ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src' but I have installed it

and this is my main.js

import Vue from 'vue';
import App from './App.vue';
import vuetify from '.plugins/vuetify';

Vue.config.productionTip = false;

new Vue({
 vuetify,
 render: (h) => h(App),
}).$mount('#app');

Body:
Use

import vuetify from './plugins/vuetify'

Notice the slightest of path difference before plugins here


问:
Switch product image on hover on WooCommerce archive page
Is there a way (maybe via functions.php) to change the product-image in woocommerce shops (archive page) on hover with the first attached gallery image of the product? I cannot find how to target both. I guess it must be sth like this:

```<code>add_action( 'woocommerce_shop_loop_item', 'change_image_on_hover', 10 );
function change_image_on_hover() {
     $product->get_gallery_image_ids();
     print 'woocommerce_gallery_image';
}
</code>```

答:
You can use the plugin if you have not removed the default action and filter of WooCommerce.

Here is the plugin link

Body:
Is there a way (maybe via functions.php) to change the product-image in woocommerce shops (archive page) on hover with the first attached gallery image of the product? I cannot find how to target both. I guess it must be sth like this:

add_action( 'woocommerce_shop_loop_item', 'change_image_on_hover', 10 );
function change_image_on_hover() {
     $product->get_gallery_image_ids();
     print 'woocommerce_gallery_image';
}


问:
Rename app in google play store
I published my app in google play store and tried to find it. But I found it by project name. My project name wasn't like app name.

But many people installed my app. How can I change the name without uploading a new app?

Project name is: quarrynew

App name is: quarry

I changed my project name and uploaded it. But it wasn't changed. I'm waiting a few days.

People can find my application by typing "quarrynew". But never find it by typing "quarry".

Application name is "quarry". Only project name and filename was "quarrynew".

```<code><string name="app_name">Quarry</string>
</code>```

答:
It is quite easy to be done.
Just follow these steps and you will be able to do in seconds.

Open Google Play Console and select the App you want to change.

Go to Store Listing and in Title Field enter the NEW NAME .

Submit at the bottom of the page.

After 24 you will be able to see the new name on the play store.

Title: Rename app in google play store

Body:
I published my app in google play store and tried to find it. But I found it by project name. My project name wasn't like app name.

But many people installed my app. How can I change the name without uploading a new app?

Project name is: quarrynew

App name is: quarry

I changed my project name and uploaded it. But it wasn't changed. I'm waiting a few days.

People can find my application by typing "quarrynew". But never find it by typing "quarry".

Application name is "quarry". Only project name and filename was "quarrynew".

<string name="app_name">Quarry</string>


问:
How to run a side task while also waiting for getch?
So I have this small program (using Linux):

```<code>import getch

while True:
  print("Hello World!")

  key = getch.getch()

  if key == 'q':
    break
</code>```

So all it does is wait for the user to hit a key, and they displays "Hello World!" to the console. However, is there a way so that I can continuously display "Hello World!" to the console, and the only way to get it to end is if the user presses the "q" key?

This question is similar to this one, but it's in C++.

My first thought was to look up threading, however, I tried all the threads I could find and none of them worked. Then I came across the Global Interpreter Lock (GIL), and it supposedly prevents "multiple native threads from executing Python bytecodes at once."

Then I tried to use multiprocessing, but it still didn't work for me. This is how far I got using it:

```<code>import multiprocessing
import getch

def test1():
  print("Hello World!")

def test2():
  key = getch.getch()

  if key == 'q':
    exit()

while True:
  p1 = multiprocessing.Process(target=test1, args=())
  p2 = multiprocessing.Process(target=test2, args=())

  p1.start()
  p2.start()

  p1.join()
  p2.join()
</code>```

Am I missing something here? Or is there another way in which I can do something while also waiting for getch()? Or do I have to write this in another language that supports multithreading like C++?

Thanks

答:
I was not able to install fetch, probably because I am on Windows at the moment, but you can implement what you want (However, is there a way so that I can continuously display "Hello World!" to the console, and the only way to get it to end is if the user presses the "q" key?) the following way:

import time
from threading import Thread

def another_thread():
    while True:
        time.sleep(2)
        print("Working...\n")

def main_thread():
    while True:
        x = input("Press a key: \n")
        if x == "q":
            break

if __name__ == '__main__':
    # create another Thread object
    # daemon means that it will stop if the Main Thread stops
    th = Thread(target=another_thread, daemon=True)
    th.start()  # start the side Thread
    main_thread()  # start main logic
```

Body:
So I have this small program (using Linux):

import getch

while True:
  print("Hello World!")

  key = getch.getch()

  if key == 'q':
    break

So all it does is wait for the user to hit a key, and they displays "Hello World!" to the console. However, is there a way so that I can continuously display "Hello World!" to the console, and the only way to get it to end is if the user presses the "q" key?

This question is similar to this one, but it's in C++.

My first thought was to look up threading, however, I tried all the threads I could find and none of them worked. Then I came across the Global Interpreter Lock (GIL), and it supposedly prevents "multiple native threads from executing Python bytecodes at once."

Then I tried to use multiprocessing, but it still didn't work for me. This is how far I got using it:

import multiprocessing
import getch

def test1():
  print("Hello World!")

def test2():
  key = getch.getch()

  if key == 'q':
    exit()

while True:
  p1 = multiprocessing.Process(target=test1, args=())
  p2 = multiprocessing.Process(target=test2, args=())

  p1.start()
  p2.start()

  p1.join()
  p2.join()

Am I missing something here? Or is there another way in which I can do something while also waiting for getch()? Or do I have to write this in another language that supports multithreading like C++?

Thanks


问:
Delete an array element based on a value that contains a date in PHP 7
I'm trying to delete array elements older than 1 month.

All array elements contains a date value which I'm trying to compare in PHP using strtotime +1 month.

The array looks like this:

```<code>[
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "4q9fenYDD3Czy2fyTkQmIlvj-1590978189-9BBNrQE5.webp",
    "gender": "female",
    "rating": 61231,
    "date": "2020-04-08 02:23:09",
    "description": ""
  },
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp",
    "gender": "male",
    "rating": 0,
    "date": "2020-06-01 03:41:38",
    "description": ""
  }
]
</code>```

I'm checking the array with the following PHP code:

```<code>$datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('+1 month',strtotime($datenow)));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate) <br>";
    if ($gotDate > $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."<br>";
        //unset ($monthlyArray[$key]);
    }
}

</code>```

Note that $monthlyArray contains the array above.

The results I get when I run this code:

```<code>Comparing Array Date: (2020-04-08 02:23:09) with Current Date +1 month: (2020-06-01 09:19:09)
Comparing Array Date: (2020-06-01 03:41:38) with Current Date +1 month: (2020-06-01 09:19:09)
</code>```

As you can see, the if ($gotDate > $expireDate) didn't get fired which is very odd because the first element in the array has a date set to 2020-04-08 02:23:09 which is indeed more than 1 month old.

What am I doing wrong?

答:
Simply compare the Dates</p>

```<code>// $datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('-1 month'));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate) <br>";
    if ($gotDate < $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."<br>";
        //unset ($monthlyArray[$key]);
    }
}
</code>```

Body:
I'm trying to delete array elements older than 1 month.

All array elements contains a date value which I'm trying to compare in PHP using strtotime +1 month.

The array looks like this:

[
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "4q9fenYDD3Czy2fyTkQmIlvj-1590978189-9BBNrQE5.webp",
    "gender": "female",
    "rating": 61231,
    "date": "2020-04-08 02:23:09",
    "description": ""
  },
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp",
    "gender": "male",
    "rating": 0,
    "date": "2020-06-01 03:41:38",
    "description": ""
  }
]

I'm checking the array with the following PHP code:

$datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('+1 month',strtotime($datenow)));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate)
";
    if ($gotDate > $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."
";
        //unset ($monthlyArray[$key]);
    }
}

Note that $monthlyArray contains the array above.

The results I get when I run this code:

Comparing Array Date: (2020-04-08 02:23:09) with Current Date +1 month: (2020-06-01 09:19:09)
Comparing Array Date: (2020-06-01 03:41:38) with Current Date +1 month: (2020-06-01 09:19:09)

As you can see, the if ($gotDate > $expireDate) didn't get fired which is very odd because the first element in the array has a date set to 2020-04-08 02:23:09 which is indeed more than 1 month old.

What am I doing wrong?

Body:
Simply compare the Dates

// $datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('-1 month'));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate) <br>";
    if ($gotDate < $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."<br>";
        //unset ($monthlyArray[$key]);
    }
}


问:
Platanus_allee genome assembler failed assebly error
I am trying to run Platanus_allee genome assembler to assemble a genome. However, when I run phase command, it gives the following error:

My command:

bio@bio-XPS-8700:~/Fareeha/Platanus/Platanus_allee_v2.0.2_Linux_x86_64$ ./platanus_allee phase -c out_contig.fa out_junctionKmer.fa \platanus_allee phase \ -c out_contig.fa out_junctionKmer.fa \ -IP1 /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_1_head-3000000.fq /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_2_head-3000000.fq \ 2>phase.log

Output :

platanus_allee version: 2.0.2

./platanus_allee phase -c out_contig.fa out_junctionKmer.fa platanus_allee phase -c out_contig.fa out_junctionKmer.fa -IP1 /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_1_head-3000000.fq /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_2_head-3000000.fq 2

```<code>Error(13): Error, SolveDBG exception!!
platanus_allee solve_DBG command failed.
</code>```

Can anyone please help me solve it ?

答:
In the phase stage of platanus2 I have solved it by installing minimap2 with conda and everything should work.</p>

```<code>conda install -c bioconda minimap2
</code>```

Body:
I am trying to run Platanus_allee genome assembler to assemble a genome. However, when I run phase command, it gives the following error:

My command:

bio@bio-XPS-8700:~/Fareeha/Platanus/Platanus_allee_v2.0.2_Linux_x86_64$ ./platanus_allee phase -c out_contig.fa out_junctionKmer.fa \platanus_allee phase \ -c out_contig.fa out_junctionKmer.fa \ -IP1 /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_1_head-3000000.fq /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_2_head-3000000.fq \ 2>phase.log

Output :

platanus_allee version: 2.0.2

./platanus_allee phase -c out_contig.fa out_junctionKmer.fa platanus_allee phase -c out_contig.fa out_junctionKmer.fa -IP1 /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_1_head-3000000.fq /home/bio/Fareeha/test/SMIX_test_data/Unzip/SDNA-270_2_head-3000000.fq 2

Error(13): Error, SolveDBG exception!!
platanus_allee solve_DBG command failed.

Can anyone please help me solve it ?

Body:
In the phase stage of platanus2 I have solved it by installing minimap2 with conda and everything should work.

conda install -c bioconda minimap2


问:
Permission review Google Play for access to background location
According to the Requesting access to background location, Google Play requires a strict(er) set of requirements to be able to use background permissions for apps installed via the Google Play store. It provides a set of guidelines which have to be fulfilled to allow an app to enter- or remain in the store with said permissions. According to the document, it states:

May: Developers can request feedback on their use case via the Play Console with an estimated reply time of two weeks.

Having adjusted the app we have in the store, we're ready for a review to see if everything is correctly implemented. The documentation states that feedback can be requested through the Play Console, but I don't see any such option. How do we go about request a reviewing so that we can keep background permissions for the continued operation of our app?

答:
I have received the following instructions from Google Support in order to submit an existing app for their evaluation against their new location policy:

https://support.google.com/googleplay/android-developer/answer/9214102?hl=en

From their email:
"When you complete the Permissions Declaration Form and roll out your release, your app will be subject to an extended review by the Google Play team. Your request may require up to several weeks to process. During this time your new app or app update will be in a pending publication status until your request is reviewed. Your app will also be subject to the standard compliance review against Google Play's Developer Program Policies.

Once your Permission Declaration has been approved and your app has been approved for policy compliance, your release will be published and you can once again use the Publishing API to manage your releases.  Otherwise, the Google Play team will notify you if your Permissions Declaration request has been rejected and provide any additional information."


问:
How to redraw MFC tooltip when a mouse is moved?
This one is a c++/MFC project.
I need to display a position of the cursor. So I must redraw tooltip everytime when a mouse is moving.
I can draw a tooltip but a tooltip was drawn isn't cleared.

The OnShowTooltip() function will be called if mouse is moving.

```<code>     void OnShowToolTip(const CPoint& ptMousePosition,CString strText)
     {
        UpdateData(true);
        if (bToolTip)
        {
         unsigned int uid = 0;       // for ti initialization
         // CREATE A TOOLTIP WINDOW
         hwndTT = CreateWindowEx(WS_EX_TOPMOST,
                            TOOLTIPS_CLASS,
                            NULL,
                            TTS_NOPREFIX ,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            NULL,
                            NULL,
                            NULL,
                            NULL
                           );

         // INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE
         //ti.cbSize = sizeof(TOOLINFO);
         ti.cbSize = TTTOOLINFO_V1_SIZE;
         ti.uFlags = TTF_TRACK;
         ti.hwnd = NULL;
         ti.hinst = NULL;
         ti.uId = uid;
         ti.lpszText = (LPSTR)(LPCSTR) strText;
         // ToolTip control will cover the whole window
         ti.rect.left = 0;
         ti.rect.top = 0;
         ti.rect.right = 0;
         ti.rect.bottom = 0;

         // SEND AN ADDTOOL MESSAGE TO THE TOOLTIP CONTROL WINDOW
         ::SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);

         ::SendMessage(hwndTT, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(ptMousePosition.x, ptMousePosition.y));
              ::SendMessage(hwndTT, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &ti);

              bToolTip=false;
     }else{
              ::SendMessage(hwndTT, TTM_TRACKACTIVATE, false, (LPARAM)(LPTOOLINFO) &ti);
              bToolTip=true;
     }
    }
</code>```

I have a function for handling mouse events like below

```<code> BOOL DoDragPoint2D(CPoint point,CString strPositions)
 {
    switch (msg.message)
    {

        case WM_MOUSEMOVE:
            bToolTip = TRUE;
            OnShowToolTip(point,strPositions);
        break;

       case WM_LBUTTONUP:
             bToolTip = FALSE;
             OnShowToolTip(point,strPositions);
    }
 }
</code>```

Although I set bTooltip to be FALSE. But It cannot to remove tooltip.
Moreover I try to call Invalidate() function but a tooltip still display until a dubbuging is stopped.

答:
Each time the mouse moves, a new tooltip is created.

You only need to create the tooltip once in WM_CREATE event.

Then send TTM_SETTOOLINFO message to update ti.lpszText.

ep.

```<code>    case WM_CREATE:
    {
        unsigned int uid = 0;       // for ti initialization
        hwndTT = CreateWindowEx(WS_EX_TOPMOST,
            TOOLTIPS_CLASS,
            NULL,
            TTS_NOPREFIX,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            NULL,
            NULL,
            NULL,
            NULL
        );

        // INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE
        //ti.cbSize = sizeof(TOOLINFO);
        ti.cbSize = TTTOOLINFO_V1_SIZE;
        ti.uFlags = TTF_TRACK;
        ti.hwnd = NULL;
        ti.hinst = NULL;
        ti.uId = uid;
        ti.lpszText = const_cast <wchar_t*>(L"");
        // ToolTip control will cover the whole window
        ti.rect.left = 0;
        ti.rect.top = 0;
        ti.rect.right = 0;
        ti.rect.bottom = 0;
        ::SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti);
    }
    break;

   case WM_MOUSEMOVE:
     ...
     ti.lpszText = (LPSTR)(LPCSTR) strText;
     ::SendMessage(hwndTT, TTM_SETTOOLINFO, 0, (LPARAM)&ti);
     ::SendMessage(hwndTT, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(ptMousePosition.x, ptMousePosition.y));
     ::SendMessage(hwndTT, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &ti);
     ...
</code>```

Body:
This one is a c++/MFC project.
I need to display a position of the cursor. So I must redraw tooltip everytime when a mouse is moving.
I can draw a tooltip but a tooltip was drawn isn't cleared.

The OnShowTooltip() function will be called if mouse is moving.

     void OnShowToolTip(const CPoint& ptMousePosition,CString strText)
     {
        UpdateData(true);
        if (bToolTip)
        {
         unsigned int uid = 0;       // for ti initialization
         // CREATE A TOOLTIP WINDOW
         hwndTT = CreateWindowEx(WS_EX_TOPMOST,
                            TOOLTIPS_CLASS,
                            NULL,
                            TTS_NOPREFIX ,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            NULL,
                            NULL,
                            NULL,
                            NULL
                           );

         // INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE
         //ti.cbSize = sizeof(TOOLINFO);
         ti.cbSize = TTTOOLINFO_V1_SIZE;
         ti.uFlags = TTF_TRACK;
         ti.hwnd = NULL;
         ti.hinst = NULL;
         ti.uId = uid;
         ti.lpszText = (LPSTR)(LPCSTR) strText;
         // ToolTip control will cover the whole window
         ti.rect.left = 0;
         ti.rect.top = 0;
         ti.rect.right = 0;
         ti.rect.bottom = 0;

         // SEND AN ADDTOOL MESSAGE TO THE TOOLTIP CONTROL WINDOW
         ::SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);

         ::SendMessage(hwndTT, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(ptMousePosition.x, ptMousePosition.y));
              ::SendMessage(hwndTT, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &ti);

              bToolTip=false;
     }else{
              ::SendMessage(hwndTT, TTM_TRACKACTIVATE, false, (LPARAM)(LPTOOLINFO) &ti);
              bToolTip=true;
     }
    }

I have a function for handling mouse events like below

 BOOL DoDragPoint2D(CPoint point,CString strPositions)
 {
    switch (msg.message)
    {

        case WM_MOUSEMOVE:
            bToolTip = TRUE;
            OnShowToolTip(point,strPositions);
        break;

       case WM_LBUTTONUP:
             bToolTip = FALSE;
             OnShowToolTip(point,strPositions);
    }
 }

Although I set bTooltip to be FALSE. But It cannot to remove tooltip.
Moreover I try to call Invalidate() function but a tooltip still display until a dubbuging is stopped.

Body:
Each time the mouse moves, a new tooltip is created.

You only need to create the tooltip once in WM_CREATE event.

Then send TTM_SETTOOLINFO message to update ti.lpszText.

ep.

    case WM_CREATE:
    {
        unsigned int uid = 0;       // for ti initialization
        hwndTT = CreateWindowEx(WS_EX_TOPMOST,
            TOOLTIPS_CLASS,
            NULL,
            TTS_NOPREFIX,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            NULL,
            NULL,
            NULL,
            NULL
        );

        // INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE
        //ti.cbSize = sizeof(TOOLINFO);
        ti.cbSize = TTTOOLINFO_V1_SIZE;
        ti.uFlags = TTF_TRACK;
        ti.hwnd = NULL;
        ti.hinst = NULL;
        ti.uId = uid;
        ti.lpszText = const_cast <wchar_t*>(L"");
        // ToolTip control will cover the whole window
        ti.rect.left = 0;
        ti.rect.top = 0;
        ti.rect.right = 0;
        ti.rect.bottom = 0;
        ::SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti);
    }
    break;

   case WM_MOUSEMOVE:
     ...
     ti.lpszText = (LPSTR)(LPCSTR) strText;
     ::SendMessage(hwndTT, TTM_SETTOOLINFO, 0, (LPARAM)&ti);
     ::SendMessage(hwndTT, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(ptMousePosition.x, ptMousePosition.y));
     ::SendMessage(hwndTT, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &ti);
     ...


问:
How to name excel files as the names of the data frames in a list in R
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

```<code>for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}
</code>```

```<code># dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )
</code>```

```<code>    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3
</code>```

答:
Names of list elements can be accessed as using names()

```<code>names(listDF)
[1] "DF1" "DF2" "DF3"
</code>```

Your loop needs to be modified to:

```<code>for (i in (1:3)) {write.xlsx(listDF[i],file=paste0(names(listDF)[i],".xlsx"))}
</code>```

Also note that using paste generates a whitespace between your DF name and .xlsx. Using paste0 discards the whitespace.

Body:
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}

# dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )

    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3

Body:
Names of list elements can be accessed as using names()

names(listDF)
[1] "DF1" "DF2" "DF3"

Your loop needs to be modified to:

for (i in (1:3)) {write.xlsx(listDF[i],file=paste0(names(listDF)[i],".xlsx"))}

Also note that using paste generates a whitespace between your DF name and .xlsx. Using paste0 discards the whitespace.


问:
Get some set of values in SQL Server
I have a query, in this query I need to get a number of classes (class count) in each district. In here it comes only those who have classes. So I need to show the district's it doesn't have a classes as well.

My District table consist 25 values. and my class coverage table has 5 values to 3 districts. I need to show all the districts.

Code

```<code>SELECT
    CC.DistrictId, D.DistrictName,
    COUNT(D.DistrictId) AS DistrictCount
FROM
    TBL_T_ClassCoverage CC
LEFT JOIN
    [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE
    CC.IsActive = 1
GROUP BY
    CC.DistrictId, D.DistrictName
ORDER BY
    DistrictId ASC
</code>```

答:
Basically you need right join not left join here.

```<code>SELECT CC.DistrictId, D.DistrictName, Count(D.DistrictId) AS DistrictCount
FROM TBL_T_ClassCoverage CC
RIGHT JOIN [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE CC.IsActive = 1
GROUP BY CC.DistrictId, D.DistrictName
ORDER BY DistrictId ASC
</code>```

Title: Get some set of values in SQL Server

Body:
I have a query, in this query I need to get a number of classes (class count) in each district. In here it comes only those who have classes. So I need to show the district's it doesn't have a classes as well.

My District table consist 25 values. and my class coverage table has 5 values to 3 districts. I need to show all the districts.

Code

SELECT
    CC.DistrictId, D.DistrictName,
    COUNT(D.DistrictId) AS DistrictCount
FROM
    TBL_T_ClassCoverage CC
LEFT JOIN
    [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE
    CC.IsActive = 1
GROUP BY
    CC.DistrictId, D.DistrictName
ORDER BY
    DistrictId ASC

Body:
Basically you need right join not left join here.

SELECT CC.DistrictId, D.DistrictName, Count(D.DistrictId) AS DistrictCount
FROM TBL_T_ClassCoverage CC
RIGHT JOIN [dbo].[TBL_M_District] D ON CC.DistrictId = D.DistrictId
WHERE CC.IsActive = 1
GROUP BY CC.DistrictId, D.DistrictName
ORDER BY DistrictId ASC


问:
Get a file from jar using index
I am trying to access a file using java.io.File from the running jar using index. I mean, like creating the array of the files in that folder and then get a file by its index. </p>

答:
jar tf file.jar command can be used to list down contents of jar file.

An example of jar tf command utitlity:

```<code>> jar tf demo-1.0.0.jar

META-INF/
META-INF/MANIFEST.MF
org/
org/springframework/
org/springframework/boot/
org/springframework/boot/loader/
...
org/springframework/boot/loader/jar/
org/springframework/boot/loader/jar/JarURL
</code>```

The same result can be obtained programmatically also, by using the java.jar.Jarfile class

Here is an example of programmatic lookup of contents of jar file:

```<code>// File name: JarLs.java
// This program lists down all the contents of a .jar file

import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.Enumeration;

public class JarLs {
    public static void main(String[] args) throws Exception {
        JarFile jarFile = new JarFile("D:/test/demo-1.0.0.jar");
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            System.out.println(jarEntries.nextElement().getName());
        }
   }
}
</code>```

Output:

```<code>> javac JarLs.java
> java JarLs

META-INF/
META-INF/MANIFEST.MF
org/
org/springframework/
org/springframework/boot/
org/springframework/boot/loader/
org/springframework/boot/loader/archive/
org/springframework/boot/loader/archive/ExplodedArchive$FileEntry.class
org/springframework/boot/loader/WarLauncher.class
...
...
BOOT-INF/
BOOT-INF/classes/
BOOT-INF/classes/com/
...
...
BOOT-INF/classes/com/demo/controller/WebTrafficController.class
BOOT-INF/classes/com/demo/SpringBootWebApplication.class
</code>```

More information:

https://docs.oracle.com/javase/tutorial/deployment/jar/view.html

http://www.devx.com/tips/java/reading-contents-of-a-jar-file-using-java.-170629013043.html

Title: Get a file from jar using index

Body:
jar tf file.jar command can be used to list down contents of jar file.

An example of jar tf command utitlity:

> jar tf demo-1.0.0.jar

META-INF/
META-INF/MANIFEST.MF
org/
org/springframework/
org/springframework/boot/
org/springframework/boot/loader/
...
org/springframework/boot/loader/jar/
org/springframework/boot/loader/jar/JarURL

The same result can be obtained programmatically also, by using the java.jar.Jarfile class

Here is an example of programmatic lookup of contents of jar file:

// File name: JarLs.java
// This program lists down all the contents of a .jar file

import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.Enumeration;

public class JarLs {
    public static void main(String[] args) throws Exception {
        JarFile jarFile = new JarFile("D:/test/demo-1.0.0.jar");
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            System.out.println(jarEntries.nextElement().getName());
        }
   }
}

Output:

> javac JarLs.java
> java JarLs

META-INF/
META-INF/MANIFEST.MF
org/
org/springframework/
org/springframework/boot/
org/springframework/boot/loader/
org/springframework/boot/loader/archive/
org/springframework/boot/loader/archive/ExplodedArchive$FileEntry.class
org/springframework/boot/loader/WarLauncher.class
...
...
BOOT-INF/
BOOT-INF/classes/
BOOT-INF/classes/com/
...
...
BOOT-INF/classes/com/demo/controller/WebTrafficController.class
BOOT-INF/classes/com/demo/SpringBootWebApplication.class

More information:

https://docs.oracle.com/javase/tutorial/deployment/jar/view.html

http://www.devx.com/tips/java/reading-contents-of-a-jar-file-using-java.-170629013043.html