问:
problem rendering image in browser FileContentResult
I want to show an image from database

I have an action

```<code> public FileContentResult GetImage(string param)

        {

      type obj  = _someRepository.GetType(param);

            if (obj!= null && obj.Image!= null)
            {

                return File(obj.Image.ToArray(), obj.Image.MimeType);
            }

            return "some default image";
        }
</code>```

in the view I have

```<code>< img src="<%:Url.Action("GetImage","ControllerName",new { param= somevalue })%>"  alt="some text"
            width="100px" height="100px" />
</code>```

I also have

```<code> (Html.BeginForm("actionname", "controllername", FormMethod.Post, new { enctype = "multipart/form-data" })
</code>```

set.

The image data is fetched from the database But I can't see the image in the browser,
is there something that I am missing?

答:
Here are the steps I would perform in order to isolate the problem. Start with a simple controller action which returns some hardcoded image somewhere from your harddrive:

```<code>public ActionResult GetImage(string param)
{
    byte[] image = File.ReadAllBytes(@"c:\work\foo.png");
    return File(image, "image/png");
}
</code>```

Now navigate directly to /ControllerName/GetImage in your browser and you should see the image.

The next step is to fetch the image from the database and probably store it on your harddisk to ensure that it is a valid image:

```<code>type obj = _someRepository.GetType(param);
File.WriteAllBytes(@"c:\work\foo.png", obj.Image.ToArray());
</code>```

Now checkout the generated file and see if it is valid. The last step is to ensure that the url generated in the  tag is the same as the one you used to test directly. Then look at FireBug's Net tab to see if the browser correctly requests the image and what does the server return.

Most probably the issue is that the byte array returned from the database is not valid image or it is empty.

As far as the form you have shown in your question, this is for uploading files, it has nothing to do with serving dynamic images from a controller action, so I don't see what relation it might have to your question.

Body:
I want to show an image from database

I have an action

 public FileContentResult GetImage(string param)

        {

      type obj  = _someRepository.GetType(param);

            if (obj!= null && obj.Image!= null)
            {

                return File(obj.Image.ToArray(), obj.Image.MimeType);
            }

            return "some default image";
        }

in the view I have

< img src="<%:Url.Action("GetImage","ControllerName",new { param= somevalue })%>"  alt="some text"
            width="100px" height="100px" />

I also have

 (Html.BeginForm("actionname", "controllername", FormMethod.Post, new { enctype = "multipart/form-data" })

set.

The image data is fetched from the database But I can't see the image in the browser,
is there something that I am missing?

Body:
Here are the steps I would perform in order to isolate the problem. Start with a simple controller action which returns some hardcoded image somewhere from your harddrive:

public ActionResult GetImage(string param)
{
    byte[] image = File.ReadAllBytes(@"c:\work\foo.png");
    return File(image, "image/png");
}

Now navigate directly to /ControllerName/GetImage in your browser and you should see the image.

The next step is to fetch the image from the database and probably store it on your harddisk to ensure that it is a valid image:

type obj = _someRepository.GetType(param);
File.WriteAllBytes(@"c:\work\foo.png", obj.Image.ToArray());

Now checkout the generated file and see if it is valid. The last step is to ensure that the url generated in the <img> tag is the same as the one you used to test directly. Then look at FireBug's Net tab to see if the browser correctly requests the image and what does the server return.

Most probably the issue is that the byte array returned from the database is not valid image or it is empty.

As far as the form you have shown in your question, this is for uploading files, it has nothing to do with serving dynamic images from a controller action, so I don't see what relation it might have to your question.


来源: stackexchange

问:
Need select option by another input value
I have two inputs one is simple input another is select input with options. How can i achieve that when someone enters value for text input it automatically select correct option.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  Job code
  <input type="text" id="test2" name="jobcode[]" class="form-control">

  Job
  <select class="form-control" name="job[]" >
      <option value="1">Administrator - 1</option>
      <option value="2">Bartender - 2</option>
      <option value="3">Mechanic - 3</option>
      <option value="4">Bodybuilder - 4</option>
      <option value="5">Doctor- 5</option>
  </select>

```

答:
Try this, here the code simply checks if the inputted value is among the options available and changes the selected option to the one whose value is the same as what was entered in the input element.

var test2 = document.getElementById("test2")
var test3 = document.querySelector("[name=job]")

test2.onchange = () => {
  if ([...test3.children].some(each => each.value == test2.value)) {
    test3.value = test2.value
  }else{
    test3.value = 1
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-md-2">
    <label class="text-black" for="test2">Job code</label>
    <input type="text" id="test2" name="jobcode[]" class="form-control">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Job</label>
    <select class="form-control" name="job">
      <option value="1">Administrator - 1</option>
      <option value="2">Bartender - 2</option>
      <option value="3">Mechanic - 3</option>
      <option value="4">Bodybuilder - 4</option>
      <option value="5">Doctor- 5</option>
    </select>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this, here the code simply checks if the inputted value is among the options available and changes the selected option to the one whose value is the same as what was entered in the input element.

var test2 = document.getElementById("test2")
var test3 = document.querySelector("[name=job]")

test2.onchange = () => {
  if ([...test3.children].some(each => each.value == test2.value)) {
    test3.value = test2.value
  }else{
    test3.value = 1
  }
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-md-2">
    <label class="text-black" for="test2">Job code</label>
    <input type="text" id="test2" name="jobcode[]" class="form-control">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Job</label>
    <select class="form-control" name="job">
      <option value="1">Administrator - 1</option>
      <option value="2">Bartender - 2</option>
      <option value="3">Mechanic - 3</option>
      <option value="4">Bodybuilder - 4</option>
      <option value="5">Doctor- 5</option>
    </select>
  </div>
</div>


问:
Aggregation pipeline "latest for all distinct id" is very slow, need to create proper indexes?
Considering the following aggregation pipeline code to return newest entry for all distinct "internal_id":

```<code>db.locations.aggregate({$sort: {timestamp: -1}}, {$group: {_id: "$internal_id", doc: {$first: "$$ROOT"}}})
</code>```

This call takes up to 10 seconds, which is not acceptable. The collection is not so huge:

```<code>db.locations.count()
1513671
</code>```

So I guess there's something wrong with the indexes, however I tried to create many indexes and none of them made an improvement, currently I kept those two that were supposed to be enough imho: {timestamp: -1, internal_id: 1}  and {internal_id: 1, timestamp: -1}.

MongoDB is NOT sharded, and running a 3 hosts replicaset running version 3.6.14.

MongoDB log show the following:

```<code>2020-05-30T12:21:18.598+0200 I COMMAND  [conn12652918] command mydb.locations appName: "MongoDB Shell" command: aggregate { aggregate: "locations", pipeline: [ { $sort: { timestamp: -1.0 } }, { $group: { _id: "$internal_id", doc: { $first: "$$ROOT" } } } ], cursor: {}, lsid: { id: UUID("70fea740-9665-4068-a2b5-b7b0f10dcde9") }, $clusterTime: { clusterTime: Timestamp(1590834060, 34), signature: { hash: BinData(0, 9DFB6DBCEE52CFA3A5832DC209519A8E9D6F1204), keyId: 6783976096153993217 } }, $db: "mydb" } planSummary: IXSCAN { timestamp: -1, ms_id: 1 } cursorid:8337712045451536023 keysExamined:1513708 docsExamined:1513708 numYields:11838 nreturned:101 reslen:36699 locks:{ Global: { acquireCount: { r: 24560 } }, Database: { acquireCount: { r: 12280 } }, Collection: { acquireCount: { r: 12280 } } } protocol:op_msg 7677msms
</code>```

答:
Mongo aggregations are theoretically descriptive (in that you describe what you want to have happen, and the query optimizer figures out an efficient way of doing that calculation), but in practice many aggregations end up being procedural & not optimized. If you take a look at the procedural aggregation instructions:

{$sort: {timestamp: -1}}: sort all documents by the timestamp.

{$group: {_id: "$internal_id", doc: {$first: "$$ROOT"}}: go through these timestamp sorted documents and then group them by the id. Because everything is sorted by timestamp at this point (rather than id), it'll end up being a decent amount of work.

You can see that this is what mongo is actually doing by taking a look at that log line's query plan: planSummary IXSCAN { timestamp: -1, ms_id: 1 }.

You want to force mongo to come up with a better query plan than that that uses the
{internal_id: 1, timestamp: -1} index. Giving it a hint to use this index might work -- it depends on how well it's able to calculate the query plan.

If providing that hint doesn't work, one altenative would be to break this query into 2 parts that each uses an appropriate index.

Find the maximum timestamp for each internal_id. db.my_collection.aggregate([{$group: {_id: "$internal_id", timestamp: {$max: "$timestamp"}}}]). This should use the {internal_id: 1, timestamp: -1} index.

Use those results to find the documents that you actually care about: db.my_collection.find({$or: [{internal_id, timestamp}, {other_internal_id, other_timestamp}, ....]}) (if there are duplicate timestamps for the same internal_id you may need to dedupe).

If you wanted to combine these 2 parts into 1, you can use a self-join on the original collection with a $lookup.

Body:
Considering the following aggregation pipeline code to return newest entry for all distinct "internal_id":

db.locations.aggregate({$sort: {timestamp: -1}}, {$group: {_id: "$internal_id", doc: {$first: "$$ROOT"}}})

This call takes up to 10 seconds, which is not acceptable. The collection is not so huge:

db.locations.count()
1513671

So I guess there's something wrong with the indexes, however I tried to create many indexes and none of them made an improvement, currently I kept those two that were supposed to be enough imho: {timestamp: -1, internal_id: 1}  and {internal_id: 1, timestamp: -1}.

MongoDB is NOT sharded, and running a 3 hosts replicaset running version 3.6.14.

MongoDB log show the following:

2020-05-30T12:21:18.598+0200 I COMMAND  [conn12652918] command mydb.locations appName: "MongoDB Shell" command: aggregate { aggregate: "locations", pipeline: [ { $sort: { timestamp: -1.0 } }, { $group: { _id: "$internal_id", doc: { $first: "$$ROOT" } } } ], cursor: {}, lsid: { id: UUID("70fea740-9665-4068-a2b5-b7b0f10dcde9") }, $clusterTime: { clusterTime: Timestamp(1590834060, 34), signature: { hash: BinData(0, 9DFB6DBCEE52CFA3A5832DC209519A8E9D6F1204), keyId: 6783976096153993217 } }, $db: "mydb" } planSummary: IXSCAN { timestamp: -1, ms_id: 1 } cursorid:8337712045451536023 keysExamined:1513708 docsExamined:1513708 numYields:11838 nreturned:101 reslen:36699 locks:{ Global: { acquireCount: { r: 24560 } }, Database: { acquireCount: { r: 12280 } }, Collection: { acquireCount: { r: 12280 } } } protocol:op_msg 7677msms


问:
Iframe video controls not clickable?
i am using that example : https://codepen.io/cyborgspaceviking/pen/BdWagp#code-area
but beside using gif files i am using videos and loading them into iframe.
But video controls not clickable.

This is my replacing html with img tag:

```<code>  <div class="resp-container">
            <iframe class="resp-iframe video" id="gif_tv_video" scrolling="no" frameborder="0" allowfullscreen="1"
              allow="autoplay; encrypted-media" src=""></iframe>
          </div>
</code>```

This is my codepen version link: https://codepen.io/affan-sheikh/pen/MWKggOe

答:
It seems overlays are overlapping, try the following:</p>

```
    .gif-tv .viewport .pixels,
    .gif-tv .viewport .meta-left,
    .gif-tv .viewport .meta-right {
        pointer-events: none;
    }
```

Title: Iframe video controls not clickable?

Body:
i am using that example : https://codepen.io/cyborgspaceviking/pen/BdWagp#code-area
but beside using gif files i am using videos and loading them into iframe.
But video controls not clickable.

This is my replacing html with img tag:

This is my codepen version link: https://codepen.io/affan-sheikh/pen/MWKggOe

Body:
It seems overlays are overlapping, try the following:

    .gif-tv .viewport .pixels,
    .gif-tv .viewport .meta-left,
    .gif-tv .viewport .meta-right {
        pointer-events: none;
    }


问:
Wordpress get_the_content() returns  markup
I have created a new custom post type and created a few sample posts in the Guttenberg editor. However when I try to echo this content out to a textarea, to allow users to edit, it displays it as html markup:

```<code><!-- wp:paragraph -->
<p>This is a test custom post content</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
</code>```

I am using the following code to output this

```<code><textarea><?php echo esc_attr(get_the_content()); ?></textarea>
</code>```

I'm assuming this is something to do with Guttenbergs blocks as it does not do this on posts with the classic editor. I'm a relative beginner to wordpress development so apologies if there is a simple function that deals with this but I can't seem to find oue.

答:
Try out this:

```<code><textarea><?php echo esc_attr(wp_strip_all_tags(get_the_content())); ?></textarea>
</code>```

wp_strip_all_tags() will remove all these tags, and since this is just textarea, and not WYSIWIG editor, you only need plain text

Title: Wordpress get_the_content() returns <!-- wp:paragraph --> markup

Body:
I have created a new custom post type and created a few sample posts in the Guttenberg editor. However when I try to echo this content out to a textarea, to allow users to edit, it displays it as html markup:

This is a test custom post content

I am using the following code to output this

<textarea><?php echo esc_attr(get_the_content()); ?></textarea>

I'm assuming this is something to do with Guttenbergs blocks as it does not do this on posts with the classic editor. I'm a relative beginner to wordpress development so apologies if there is a simple function that deals with this but I can't seem to find oue.

Body:
Try out this:

<textarea><?php echo esc_attr(wp_strip_all_tags(get_the_content())); ?></textarea>

wp_strip_all_tags() will remove all these tags, and since this is just textarea, and not WYSIWIG editor, you only need plain text


问:
Returning multiple items from a function call in PHP
Is it possible to return multiple items from a function - and assign them to several variables in a single statement - like can be done in some languages (e.g. Python) ?

For example, can I have something like this:

```<code>a, b, c,d = foo();
</code>```

答:
Tou can do it if you`ll return an array in function and then use list construction:</p>

```<code>function foo(){
    ...
    return array('a', 'b', 'c');
}

list($a, $b, $c) = foo();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to return multiple items from a function - and assign them to several variables in a single statement - like can be done in some languages (e.g. Python) ?

For example, can I have something like this:

a, b, c,d = foo();

Body:
Tou can do it if you`ll return an array in function and then use list construction:

function foo(){
    ...
    return array('a', 'b', 'c');
}

list($a, $b, $c) = foo();


问:
Pylint in VSCode goes mad when importing third-party moudles installed with pipenv by throwing no-member errors
I've got a pipenv virtualenv. I've added it to workplace settings:

```<code>"python.pythonPath": "/home/keddad/.local/share/virtualenvs/test-8gFlsF9b/bin/python",
</code>```

It works, more or less. It starts a terminal in the pipenv by default, and it works flawlessly when I work with built-in modules. But if I install a module with pipenv, it starts working somehow strange. Let's say I've installed pydantic, import it and use like this:

```<code>import pydantic
class Foo(pydantic.BaseModel):
    bar: str
</code>```

If I just run it, it works. Hinting in editor also works. But pylint marks this code as an error:

```<code>Module 'pydantic' has no 'BaseModel' member pylint(no-member)
</code>```

Same thing happens if I just do

```<code>from pydantic import BaseModel
</code>```

I've tried creating an .env file in project directory to specify PYTHONPATH in it like in one of the answers in this question, but it didn't really help. How do I fix this?

答: Well, as a workaround, one might try using another linter. flake8 works fine, for example

Body:
I've got a pipenv virtualenv. I've added it to workplace settings:

"python.pythonPath": "/home/keddad/.local/share/virtualenvs/test-8gFlsF9b/bin/python",

It works, more or less. It starts a terminal in the pipenv by default, and it works flawlessly when I work with built-in modules. But if I install a module with pipenv, it starts working somehow strange. Let's say I've installed pydantic, import it and use like this:

import pydantic
class Foo(pydantic.BaseModel):
    bar: str

If I just run it, it works. Hinting in editor also works. But pylint marks this code as an error:

Module 'pydantic' has no 'BaseModel' member pylint(no-member)

Same thing happens if I just do

from pydantic import BaseModel

I've tried creating an .env file in project directory to specify PYTHONPATH in it like in one of the answers in this question, but it didn't really help. How do I fix this?


问:
Javascript use single await in ternary operator
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

```<code>const val = checkCondition ? "literal value" : await promiseGetValue();
</code>```

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?

答:
you can use this syntax,
However you should always use await inside async function.
You can return any value from function you are awaiting for(its not necessary to be promise, but it doesn't make sense to use await on function which is not returning promise)

function promiseGetValue() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('any value')
        })
    })
}
const flag = false
async function main() {
    const val = flag ? "literal value" : await promiseGetValue();
    console.log(val)
}
main()```

Body:
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

const val = checkCondition ? "literal value" : await promiseGetValue();

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?


问:
How do I connect to a new Amazon Lightsail instance from my Mac?
I've created a new NodeJS instance on Amazon Lightsail, and wish to connect to it from my Mac's command line. Not sure how to include the required SSH key in the connection command when it says Permission denied (publickey).

答:
To be able to connect to your amazon lightsail instance you need to download the key first.

Go to Accounts > SSH Keys (
https://lightsail.aws.amazon.com/ls/webapp/account/keys ) >
Download
(Make sure that you download the key for the same region where your instance is installed.)

Save it in a folder in your local machine. For Example- "Desktop > keys"

Open the terminal and navigate to the directory where the key is stored(cd desktop/keys )

Enter this command in terminal: chmod 600 keyfilename.pem (replace keyfile name with your actual key name e.g chmod 600 LightsailDefaultKey-eu-west-2.pem )

It is required that your private key files are NOT accessible by others.
This is why we have to change the file permissions

Run this command ssh -i keyfilename.pem username@ip
replace keyfilename.pem with your actual file name, username with your username(e.g bitnami or user) and replace IP with actual IP

You can find your IP and username on your instance page (https://lightsail.aws.amazon.com/ls/webapp/home/instances > Select Instance> Manage)


问:
Angular, Automate user page creation
currently I'm building a web app. I have been following a guide that incorporates data to localstorage. Currently I can register. However now I want to be able to create a public html page for that person at the same time.  the user instance contains things like email and username etc.

```<code>function register() {
            const user = body

            if (users.find(x => x.username === user.username)) {
                return error('Username "' + user.username + '" is already taken')
            }

            user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1;
            users.push(user);
            localStorage.setItem('users', JSON.stringify(users)); //////

            return ok();
        }
</code>```

where I've added the //////. Is there any way to grab this data and automatically create a html page with the newly registered data? I've created links to these pages but I'm hoping there is a method to add a new page, like a personal home page.

The html pages should be named users/${id}.

Thanks, any help is appreciated.

答:
If I understood correctly, you want to navigate the user to the dashboard creating the account.

For this, you will need to create a component that will act as a page, and define a route to it that can accept the ID as a parameter, something like:

{ path: 'users/:id', component: DashboardComponent }

So after the user create his account, you can navigate him to users/ID which will show the DashboardComponent that will use this ID to get his unique properties and display it to the user.

router.navigate(['/users', id]); or [routerLink]="['/users', user.id]"

You can find all the info you need for the routing here: https://angular.io/guide/router

Another good tutorial for route params here: https://angular-2-training-book.rangle.io/routing/routeparams

Title: Angular, Automate user page creation

Body:
currently I'm building a web app. I have been following a guide that incorporates data to localstorage. Currently I can register. However now I want to be able to create a public html page for that person at the same time.  the user instance contains things like email and username etc.

function register() {
            const user = body

            if (users.find(x => x.username === user.username)) {
                return error('Username "' + user.username + '" is already taken')
            }

            user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1;
            users.push(user);
            localStorage.setItem('users', JSON.stringify(users)); //////

            return ok();
        }

where I've added the //////. Is there any way to grab this data and automatically create a html page with the newly registered data? I've created links to these pages but I'm hoping there is a method to add a new page, like a personal home page.

The html pages should be named users/${id}.

Thanks, any help is appreciated.


问:
How to evaluate a dynamic variable in a docker-compose.yml file?
I want to suffix a file name with the current date in my docker-compose.yml file. The end goal being a file such as my_log_123456789.log, where 123456789 is the current unix date.

I tried using an .env file, but that did not evaluate as expected. My attempt was:

```<code># .env
NOW="$(date +%s)"
</code>```

```<code># docker-compose.yml
version: '3.8'
services:
  xxx:
      container_name: xxx
      image: xxx/xxx
      volumes:
        - /home/ubuntu/xxx_"$(NOW)".log:/home/ubuntu/xxx.log
      ...
</code>```

I tried a few variations of this and had the following issues:

ERROR: Invalid interpolation format for "volumes" option in service "xxx": "/home/ubuntu/xxx_$(NOW).log:/home/ubuntu/xxx.log"

A directory was created that was named 'xxx_"$(date +%s)".log'

How can I append the current date to a log file in a docker-compose.yml file?

答:
No, docker doesn't have a "dynamic" variable - the text from --env-file is read by docker as it is, literally, leading and trailing ' or " are removed, without any interpretation and expansions done by shell.

Create another script that will export the variable value to docker-compose or will edit the content of your variable in your .env file before calling docker-compose.

Body:
I want to suffix a file name with the current date in my docker-compose.yml file. The end goal being a file such as my_log_123456789.log, where 123456789 is the current unix date.

I tried using an .env file, but that did not evaluate as expected. My attempt was:

# .env
NOW="$(date +%s)"

# docker-compose.yml
version: '3.8'
services:
  xxx:
      container_name: xxx
      image: xxx/xxx
      volumes:
        - /home/ubuntu/xxx_"$(NOW)".log:/home/ubuntu/xxx.log
      ...

I tried a few variations of this and had the following issues:

ERROR: Invalid interpolation format for "volumes" option in service "xxx": "/home/ubuntu/xxx_$(NOW).log:/home/ubuntu/xxx.log"

A directory was created that was named 'xxx_"$(date +%s)".log'

How can I append the current date to a log file in a docker-compose.yml file?


问:
convert gwiki (old GoogleCode wiki) to something new e.g. markdown
I'm struggling to find a a proper way to convert my old GoogleCode Wikis to GitHub Wiki.

I've tried pandoc and txt2tags so far with no success. Essentially, I can't find what format Google Code wikis used. I need something to properly convert to, e.g., markdown, things like:

```<code>= HEAD =

* Bullet

*Bold*

* *Bold text in a bullet*

~~strikeout~~

_italic_

`code`

[http://www.example.com A link]
</code>```

I've tried my example above in https://pandoc.org/try for all possible input formats and the closest I got was:

pandoc --from vimwiki --to gfm

But it misses URLs and I don't like its bold solution with **Bold** (it should be just **Bold**).

Using txt2tags, I got close too with:

txt2tags -v -t md my_example.gwiki

Yet, it swaps URL with text and bold renders as italic.

答:
As far as I know that isn't a standard markup language. It might have been specific to Google Code.

There is a very old¹ project called gcw2html that claims to do what you want:

A simple command-line utility to convert Google Code wiki markup to HTML using wikiwm (sic), a JavaScript Google Code wiki library.

Its README even shows how to pipe its output into Pandoc and Ruby to generate Markdown (though Pandoc has changed a lot since 2011 and you might have to adjust):

gcw2html filename.wiki \
  | pandoc --from html --to markdown --no-wrap \
  | ruby -e 'puts STDIN.readlines.to_s.gsub(/\[([^\]]*)\]\(http:\/\/code\.google\.com\/p\/[^\/]*\/wiki\/([^\)]*)\)/,"[[\\1 | \\2]]")'
```

There is also an archived Python project called statwiki that claims to generate HTML from Google Code wiki-formatted content. It was originally taken from MoinMoin and then

Slightly modify the syntax to match Google's Code Wiki Syntax

From HTML, you should be able to generate Markdown using Pandoc as shown above, though statwiki may not read from stdin and print to stdout. Its archived source code is available for download.

¹One release, version 0.1.0, came out in August, 2011. There is a single contributor.

Body:
I'm struggling to find a a proper way to convert my old GoogleCode Wikis to GitHub Wiki.

I've tried pandoc and txt2tags so far with no success. Essentially, I can't find what format Google Code wikis used. I need something to properly convert to, e.g., markdown, things like:

= HEAD =

* Bullet

*Bold*

* *Bold text in a bullet*

~~strikeout~~

_italic_

`code`

[http://www.example.com A link]

I've tried my example above in https://pandoc.org/try for all possible input formats and the closest I got was:

pandoc --from vimwiki --to gfm

But it misses URLs and I don't like its bold solution with **Bold** (it should be just **Bold**).

Using txt2tags, I got close too with:

txt2tags -v -t md my_example.gwiki

Yet, it swaps URL with text and bold renders as italic.

Body:
As far as I know that isn't a standard markup language. It might have been specific to Google Code.

There is a very old¹ project called gcw2html that claims to do what you want:

A simple command-line utility to convert Google Code wiki markup to HTML using wikiwm (sic), a JavaScript Google Code wiki library.

Its README even shows how to pipe its output into Pandoc and Ruby to generate Markdown (though Pandoc has changed a lot since 2011 and you might have to adjust):

gcw2html filename.wiki \
  | pandoc --from html --to markdown --no-wrap \
  | ruby -e 'puts STDIN.readlines.to_s.gsub(/\[([^\]]*)\]\(http:\/\/code\.google\.com\/p\/[^\/]*\/wiki\/([^\)]*)\)/,"[[\\1 | \\2]]")'

There is also an archived Python project called statwiki that claims to generate HTML from Google Code wiki-formatted content. It was originally taken from MoinMoin and then

Slightly modify the syntax to match Google's Code Wiki Syntax

From HTML, you should be able to generate Markdown using Pandoc as shown above, though statwiki may not read from stdin and print to stdout. Its archived source code is available for download.

¹One release, version 0.1.0, came out in August, 2011. There is a single contributor.


问:
cdkDragPreview and cdkDragPlaceholder not working as expected with horizontal elements
I'm using display-inline in my elements as I want them to lay out horizontally instead of vertically as they do in most of the Angular examples.  That said, the CSS behaves very weird.  I'm specifically having two issues.

When I click an element to drag it, it grows (shrinks back to regular size after dropped).  I'm not sure exactly why this happens but it is definitely not desired.  I've tried numerous things to fix this via both css and adding a cdkDragPreview element with matchSize present (this seems to be the method Angular recommends).  All of those efforts failed.  I came across the following bug report that seems similar to my issue:  https://github.com/angular/components/issues/19060.  I noted that the bug was closed, so I don't know if that means it has been fixed.

When I start to drag an element from the bottom drop list, the remaining items move around sporadically while that element is still in the drop list (when it goes out of the bottom drop list they behave as I would expect them to).  I created a hide style for the cdkDragPlaceholder as this seems to be how Angular provides control of this but it only helped with the top drop lists and seemed to have no effect on the bottom.

Here is a link that illustrates both issues on StackBlitz:  https://stackblitz.com/edit/spuzzler.  I'm guessing that my issue can be fixed with CSS, but I can't figure out how.

答:
Create a cdkDropList for each word. My idea is to have an outer div and an inner div that is really the element that is dragged. More over, I fixed the size of the outer div. So, when you drag, there's no re-order of the words (simply leaves an empty space instead of the word you drag)

You can see the result in this stackblitz

```<code><div #contenedor class="categories" cdkDropListGroup>
    <ng-container *ngFor="let item of items;let i=index">
        <div class="categories-item" cdkDropList
    cdkDropListOrientation="horizontal"
    [cdkDropListData]="{item:item,index:i}" (cdkDropListDropped)="drop($event)" >
            <div class="inner"  cdkDrag>
        <div *cdkDragPlaceholder></div>
        <div class="categories-item-drag" *cdkDragPreview matchSize="true" >
          <div class="inner">{{item}}</div>
        </div>
        {{item}}
        </div>
        </div>
    </ng-container>
</div>
</code>```

I use an observable that returns an array or words. In subscribe I equal to item and, using a setTimeout() add the size to the outter div

```<code>export class AppComponent implements OnInit {
  @ViewChildren(CdkDropList, { read: ElementRef }) pills: QueryList<ElementRef>;
  constructor(private renderer: Renderer2) {}
  items: any[];
  positions: any[];
  ngOnInit() {
    this.getParragraf().subscribe(res => {
      this.items = res;
      setTimeout(() => {
        this.pills.forEach(x => {
          this.renderer.setStyle(
            x.nativeElement,
            "width",
            x.nativeElement.getBoundingClientRect().width + "px"
          );
        });
      });
    });
  }

  drop(event: CdkDragDrop<any>) {
    this.items.splice(event.previousContainer.data.index, 1);
    this.items.splice(event.container.data.index,0,event.previousContainer.data.item)
    /* if we want to interchange the words, replace the two lines by*/
    //this.items[event.previousContainer.data.index]=event.container.data.item
    //this.items[event.container.data.index]=event.previousContainer.data.item
    //event.currentIndex=0;

  }

  getParragraf() {
    return of(
      "Let him who walks in the dark, who has no light, trust in the name of the Lord and rely on his God.".split(
        " "
      )
    );
  }
}
</code>```

Updated Really you needn't make a cdkDropListGroup, you can take advantage of [cdkDropListConnectedTo]. For this, you have two arrays: words and items

if res is an array of strings, you can have

```<code>  this.items = res.map((x,index)=>({value:x,ok:false,id:'id'+index}));
  this.words=res.map(x=>({o:Math.random(),value:x}))
             .sort((a,b)=>a.o-b.o)
             .map(x=>(
               {value:x.value,
               connected:this.items.filter(w=>x.value==w.value).map(x=>x.id)
               }))
</code>```

and use item.value,item.id and word.value,word.connected

See a new stackblitz

Body:
Create a cdkDropList for each word. My idea is to have an outer div and an inner div that is really the element that is dragged. More over, I fixed the size of the outer div. So, when you drag, there's no re-order of the words (simply leaves an empty space instead of the word you drag)

You can see the result in this stackblitz

<div #contenedor class="categories" cdkDropListGroup>
    <ng-container *ngFor="let item of items;let i=index">
        <div class="categories-item" cdkDropList
    cdkDropListOrientation="horizontal"
    [cdkDropListData]="{item:item,index:i}" (cdkDropListDropped)="drop($event)" >
            <div class="inner"  cdkDrag>
        <div *cdkDragPlaceholder></div>
        <div class="categories-item-drag" *cdkDragPreview matchSize="true" >
          <div class="inner">{{item}}</div>
        </div>
        {{item}}
        </div>
        </div>
    </ng-container>
</div>

I use an observable that returns an array or words. In subscribe I equal to item and, using a setTimeout() add the size to the outter div

export class AppComponent implements OnInit {
  @ViewChildren(CdkDropList, { read: ElementRef }) pills: QueryList<ElementRef>;
  constructor(private renderer: Renderer2) {}
  items: any[];
  positions: any[];
  ngOnInit() {
    this.getParragraf().subscribe(res => {
      this.items = res;
      setTimeout(() => {
        this.pills.forEach(x => {
          this.renderer.setStyle(
            x.nativeElement,
            "width",
            x.nativeElement.getBoundingClientRect().width + "px"
          );
        });
      });
    });
  }

  drop(event: CdkDragDrop<any>) {
    this.items.splice(event.previousContainer.data.index, 1);
    this.items.splice(event.container.data.index,0,event.previousContainer.data.item)
    /* if we want to interchange the words, replace the two lines by*/
    //this.items[event.previousContainer.data.index]=event.container.data.item
    //this.items[event.container.data.index]=event.previousContainer.data.item
    //event.currentIndex=0;

  }

  getParragraf() {
    return of(
      "Let him who walks in the dark, who has no light, trust in the name of the Lord and rely on his God.".split(
        " "
      )
    );
  }
}

Updated Really you needn't make a cdkDropListGroup, you can take advantage of [cdkDropListConnectedTo]. For this, you have two arrays: words and items

if res is an array of strings, you can have

  this.items = res.map((x,index)=>({value:x,ok:false,id:'id'+index}));
  this.words=res.map(x=>({o:Math.random(),value:x}))
             .sort((a,b)=>a.o-b.o)
             .map(x=>(
               {value:x.value,
               connected:this.items.filter(w=>x.value==w.value).map(x=>x.id)
               }))

and use item.value,item.id and word.value,word.connected

See a new stackblitz


答:
Yes it is possible. You can return an array from the function and use the using the list construct to assign the array elements to variables in one statement:

```<code>function fun() {
        return array(1,2,3);
}

// this will assign 1 to $a, 2 to $b and 3 to $c.
list($a,$b,$c) = fun();
</code>```

See it

Title: Returning multiple items from a function call in PHP

Body:
Yes it is possible. You can return an array from the function and use the using the list construct to assign the array elements to variables in one statement:

function fun() {
        return array(1,2,3);
}

// this will assign 1 to $a, 2 to $b and 3 to $c.
list($a,$b,$c) = fun();

See it


问:
How could I use case within join and union?
I have 2 tables:

Matches

```<code>CREATE TABLE rounds (
  `roundid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `roundname` VARCHAR(45) NULL);
</code>```

Rounds

```<code>CREATE TABLE matches (
  `matchid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `matchwinner` VARCHAR(45) NULL,
  `roundid` INT NOT NULL,
  CONSTRAINT `fk_matches_rounds`
    FOREIGN KEY (`roundid`)
    REFERENCES `mydb`.`rounds` (`roundid`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);
</code>```

Inserts

```<code>INSERT INTO rounds (`roundid`, `roundname`) VALUES (1, 'Final');
INSERT INTO rounds (`roundid`, `roundname`) VALUES (2, '3rd place');
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (1, 'fnatic', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (2, 'astralis', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (3, 'fnatic', 2);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (4, 'fnatic', 2);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (5, 'astralis', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (6, 'astralis', 1);
</code>```

My query:

```<code>SELECT
    m.matchid,
    m.matchwinner Team,
    CASE r.roundname
        WHEN r.roundname = 'Final' THEN '1st'
        ELSE '2'
    END Place
FROM
    matches m
        JOIN rounds r ON m.roundid = r.roundid
WHERE
    r.roundname = 'Final'
UNION SELECT
    m.matchid,
    m.matchwinner Team,
    CASE r.roundname
        WHEN r.roundname = '3rd place' THEN '3rd'
        ELSE '4th'
    END Place
FROM
    matches m
        JOIN rounds r ON m.roundid = r.roundid
WHERE
    r.roundname = '3rd place';
</code>```

I would like to know

what places a particular team achieved (should probably use HAVING m.matchwinner = 'fnatic')

MatchID - Team - Place

1 - fnatic - 1st

3 - fnatic - 3rd

4 - fnatic - 3rd

what places all teams achieved

MatchID - Team - Place

1 - fnatic - 1st

2 - astralis - 1st

3 - fnatic - 3rd

4 - fnatic - 3rd

and so on

Don't understand why my query isn't working?

答:
This looks like a join and conditional logic:

```<code>select
    m.matchid,
    m.matchwinner team,
    case r.roundname
        when 'Final'     then '1st'
        when '3rd place' then '3rd'
    end place
from rounds r
inner join matches m on m.roundid = r.roundid
where m.matchwinner = 'fnatic'
order by m.matchid
</code>```

To get the same result for all teams, just remove the where clause.

Demo on DB Fiddle:

```
matchid | team   | place
------: | :----- | :----
      1 | fnatic | 1st
      3 | fnatic | 3rd
      4 | fnatic | 3rd
```

Body:
I have 2 tables:

Matches

CREATE TABLE rounds (
  `roundid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `roundname` VARCHAR(45) NULL);

Rounds

CREATE TABLE matches (
  `matchid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `matchwinner` VARCHAR(45) NULL,
  `roundid` INT NOT NULL,
  CONSTRAINT `fk_matches_rounds`
    FOREIGN KEY (`roundid`)
    REFERENCES `mydb`.`rounds` (`roundid`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

Inserts

INSERT INTO rounds (`roundid`, `roundname`) VALUES (1, 'Final');
INSERT INTO rounds (`roundid`, `roundname`) VALUES (2, '3rd place');
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (1, 'fnatic', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (2, 'astralis', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (3, 'fnatic', 2);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (4, 'fnatic', 2);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (5, 'astralis', 1);
INSERT INTO matches (`matchid`, `matchwinner`, `roundid`) VALUES (6, 'astralis', 1);

My query:

SELECT
    m.matchid,
    m.matchwinner Team,
    CASE r.roundname
        WHEN r.roundname = 'Final' THEN '1st'
        ELSE '2'
    END Place
FROM
    matches m
        JOIN rounds r ON m.roundid = r.roundid
WHERE
    r.roundname = 'Final'
UNION SELECT
    m.matchid,
    m.matchwinner Team,
    CASE r.roundname
        WHEN r.roundname = '3rd place' THEN '3rd'
        ELSE '4th'
    END Place
FROM
    matches m
        JOIN rounds r ON m.roundid = r.roundid
WHERE
    r.roundname = '3rd place';

I would like to know

what places a particular team achieved (should probably use HAVING m.matchwinner = 'fnatic')

MatchID - Team - Place

1 - fnatic - 1st

3 - fnatic - 3rd

4 - fnatic - 3rd

what places all teams achieved

MatchID - Team - Place

1 - fnatic - 1st

2 - astralis - 1st

3 - fnatic - 3rd

4 - fnatic - 3rd

and so on

Don't understand why my query isn't working?

Body:
This looks like a join and conditional logic:

select
    m.matchid,
    m.matchwinner team,
    case r.roundname
        when 'Final'     then '1st'
        when '3rd place' then '3rd'
    end place
from rounds r
inner join matches m on m.roundid = r.roundid
where m.matchwinner = 'fnatic'
order by m.matchid

To get the same result for all teams, just remove the where clause.

Demo on DB Fiddle:

matchid | team   | place
------: | :----- | :----
      1 | fnatic | 1st
      3 | fnatic | 3rd
      4 | fnatic | 3rd


问:
LibGDX -class TagGame contains a signature 'LArrayList<>;' ill-formed at position 11
I have no idea what's wrong. The error came up after I tried to use an ArrayList to store Player types. I've since erased everything I did, which was only three lines, but the error won't go away.

I tried restarting Eclipse, cleaning/rebuilding, and refreshing. Still there. The only thing I haven't done is move all the code to a brand-new project, but that's a huge pain in the butt so I'd like to avoid that. And I would like to know what causes this error so as to avoid it in the future.

This is how I used the ArrayList:

```<code>ArrayList<Player> players;
...
public void create() {
    players = new ArrayList<Player>();

    players.add(p1);
    players.add(p2);
}
</code>```

This has worked in other applications, so I don't see why it should be different with LibGDX. Or why the error won't go away after erasing everything to do with it.

Edit: the error occurs on the letter "p" of "package" in the DesktopLauncher class. The ArrayList is in the main Game class.

Edit 2: if I try to run it, the console outputs Error: Could not find or load main class com.fun.tag.desktop.DesktopLauncher. The file exists, for sure, and could be opened before the error came up - literally nothing changed in the project other than four small lines. Those lines were never even compiled.

答: I just does the maven clean for entire project and it worked for me.</p>

Body:
I have no idea what's wrong. The error came up after I tried to use an ArrayList to store Player types. I've since erased everything I did, which was only three lines, but the error won't go away.

I tried restarting Eclipse, cleaning/rebuilding, and refreshing. Still there. The only thing I haven't done is move all the code to a brand-new project, but that's a huge pain in the butt so I'd like to avoid that. And I would like to know what causes this error so as to avoid it in the future.

This is how I used the ArrayList:

ArrayList<Player> players;
...
public void create() {
    players = new ArrayList<Player>();

    players.add(p1);
    players.add(p2);
}

This has worked in other applications, so I don't see why it should be different with LibGDX. Or why the error won't go away after erasing everything to do with it.

Edit: the error occurs on the letter "p" of "package" in the DesktopLauncher class. The ArrayList is in the main Game class.

Edit 2: if I try to run it, the console outputs Error: Could not find or load main class com.fun.tag.desktop.DesktopLauncher. The file exists, for sure, and could be opened before the error came up - literally nothing changed in the project other than four small lines. Those lines were never even compiled.


问:
GNU GCC Intel i5 optimization settings?
I have a Microsoft Surface Pro (5th Generation) with the i5 processor and use the GNU GCC Compiler.
Now I want to use optimization settings for this compiler and I don't know what settings are "working" with my processor.

Overview of my system:

Microsoft Surface Pro

Intel Core i5-7300U CPU @ 2,60 GHz

Microsoft Windows 10 Pro | 64-bit | Version 10.0.18363

IDE: Code::Blocks 20.03

Does anyone has an a similar system? Thanks in advance.

Kind Regards

randomcoder

答:
You can always use the flag -march=native, which tells the compiler to detect the CPU of the computer that's being used to compile, and optimize the code for that type of CPU.  This is ideal when you are compiling on the same machine you will be running the code on. Note that the resulting executable will not necessarily work on other computers with different CPUs.

Of course, you also have to use one of the -O options, typically -O2, to get optimizations at all.  There are many other specific optimization options, but whether they are helpful will depend on what your program actually does.

Title: GNU GCC Intel i5 optimization settings?


问:
How to create an array for storing x and y coordinates in Python
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

```<code>#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)
</code>```

答:
This could get you started; this shows the reading of the elements from the file.  You should be able to fill in the rest, with regard to processing the list 'each'. Here, we are splitting the input based on the ")" character, and then splitting each of those into a format that you can use; you need N-S-E-W, and a value, correct?  Might want to use a .upper or other tweak so that you don't have to worry about case ('e' vs 'E')...

Note that you were looking at the length of A, which was 2, not the number of points len(A[0])-1; you need to duplicate the first point for the formula to work:

https://www.mathopenref.com/coordpolygonarea.html

You also didn't have a return statement in your function.

```<code>#Function for computing area of a polygen
def polygonArea(A):
    n = len(A[0])-1  # of corners; added a point at end for calc
    print("corners in A = ", n)
    area = 0.0
    for i in range(0,n):
        x1=A[0][i]
        y1=A[1][i]
        x2=A[0][i+1]
        y2=A[1][i+1]
        print(i, "..." , x1,y1," ", x2,y2)
        da=(x1*y2-y1*x2)
        print(da)
        area=area+da
    print(area)
    area = abs(area) / 2.0
    return(area)

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
# file = input('Enter file name:')
file = 'data2.txt'
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""

    points = fileContent.split(')')

    for idx, each in enumerate(points):
        found_left=each.find("(")
        if(found_left > 0):
            coordinate = each[found_left+1:].split(",")
            direction=coordinate[0]
            value=coordinate[1]
            print(idx, "dir = ",  direction, " val = " , value)

            if direction == "N":
                    yb += float(value)
                    A[1].append(yb) #Storing the value in y co ordinate of vector A
                    A[0].append(xa) #Storing the value in x co ordinate of vector A
            elif direction == "W":
                     xa -= float(value)
                     A[1].append(yb)
                     A[0].append(xa)
            elif direction == "E":
                    xa += float(value)
                    A[1].append(yb)
                    A[0].append(xa)
            elif direction == "S":
                    yb -= float(value)
                    A[1].append(yb)
                    A[0].append(xa)
            else:
                print("error")

# last point is first point, needed for calculation
A[0].append(A[0][0])
A[1].append(A[1][0])

print("done reading.")
#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)
</code>```

Body:
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)

Body:
This could get you started; this shows the reading of the elements from the file.  You should be able to fill in the rest, with regard to processing the list 'each'. Here, we are splitting the input based on the ")" character, and then splitting each of those into a format that you can use; you need N-S-E-W, and a value, correct?  Might want to use a .upper or other tweak so that you don't have to worry about case ('e' vs 'E')...

Note that you were looking at the length of A, which was 2, not the number of points len(A[0])-1; you need to duplicate the first point for the formula to work:

https://www.mathopenref.com/coordpolygonarea.html

You also didn't have a return statement in your function.

#Function for computing area of a polygen
def polygonArea(A):
    n = len(A[0])-1  # of corners; added a point at end for calc
    print("corners in A = ", n)
    area = 0.0
    for i in range(0,n):
        x1=A[0][i]
        y1=A[1][i]
        x2=A[0][i+1]
        y2=A[1][i+1]
        print(i, "..." , x1,y1," ", x2,y2)
        da=(x1*y2-y1*x2)
        print(da)
        area=area+da
    print(area)
    area = abs(area) / 2.0
    return(area)

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
# file = input('Enter file name:')
file = 'data2.txt'
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""

    points = fileContent.split(')')

    for idx, each in enumerate(points):
        found_left=each.find("(")
        if(found_left > 0):
            coordinate = each[found_left+1:].split(",")
            direction=coordinate[0]
            value=coordinate[1]
            print(idx, "dir = ",  direction, " val = " , value)

            if direction == "N":
                    yb += float(value)
                    A[1].append(yb) #Storing the value in y co ordinate of vector A
                    A[0].append(xa) #Storing the value in x co ordinate of vector A
            elif direction == "W":
                     xa -= float(value)
                     A[1].append(yb)
                     A[0].append(xa)
            elif direction == "E":
                    xa += float(value)
                    A[1].append(yb)
                    A[0].append(xa)
            elif direction == "S":
                    yb -= float(value)
                    A[1].append(yb)
                    A[0].append(xa)
            else:
                print("error")

# last point is first point, needed for calculation
A[0].append(A[0][0])
A[1].append(A[1][0])

print("done reading.")
#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)


问:
Sendkeys to the right custom Excel ribbon
I'm working with a custom Excel add-in that unfortunately doesn't expose its functions to VBA, so I'm resorting to a SendKeys approach (see picture). Excel assigns Y1 to the Help ribbon, and all the other custom add-ins get assigned Y2, Y3, etc.  Thankfully, it looks like these shortcut keys are consistent internationally (Japan, LatAm).

The issue is that depending on the installation order, custom ribbons will get assigned a different shortcut key for different users.

I'm looking for a way to identify the position of "DataFlow" ribbon in Excel so I can SendKeys to the right ribbon.  Thanks in advance!

答:
The Excel extensibility model doesn't provide anything for that. You can try using the Microsoft Active Accessibility technology to identify where tab controls are located and their properties.

The Fluent UI provides the IRibboUI.ActivateTab method which activates the specified custom tab. You just need to specify the identifier of the custom Ribbon tab to be activated.


问:
403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied
I have my website. First time I can successfully login.

Default address:

```<code>www.abc.com
</code>```

I typed this on browser and I redirected to my login page:

```<code>www.abc.com/pages/landingpage.aspx
</code>```

I entered my login credential and log into the site.

After some time I opened a new tab and enter my website address

```<code>www.abc.com
</code>```

Now it gives me an error:

403 - Forbidden: Access is denied.

You do not have permission to view this directory or page using
the credentials that you supplied.

The whole story is this: if I am not logged on my site, then I can open my site number of tabs and browsers. But as soon as I logged in my site, I am getting the error above.

```<code> <authentication mode="Forms">
  <forms name="MMFormAUTH" loginUrl="Pages/LandingPage.aspx" defaultUrl="Pages/LandingPage.aspx" timeout="60" protection="All" slidingExpiration="true" enableCrossAppRedirects="false" requireSSL="false" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>
<sessionState cookieless="false" cookieName="abc" mode="InProc" timeout="60">
</sessionState>
<httpRuntime maxRequestLength="1000240" executionTimeout="120" />
</code>```

答:
Resolution for 404 Forbidden in recent .Net 4.7 MVC/webform pplication hosting in Azure VM
We need to install the .Net 4.7 and extensibilty and development in server role other than the .Net 4.7/version feature as below:
This might have been alreday activated
.Net Activated feature

We need to also add the below under IIS webserver role-> Application Development -> select the .Net version as below
Image to Activate the requited Role under IIS webserver Role
Server Role Activation under application Development

Body:
I have my website. First time I can successfully login.

Default address:

www.abc.com

I typed this on browser and I redirected to my login page:

www.abc.com/pages/landingpage.aspx

I entered my login credential and log into the site.

After some time I opened a new tab and enter my website address

www.abc.com

Now it gives me an error:

403 - Forbidden: Access is denied.

You do not have permission to view this directory or page using
the credentials that you supplied.

The whole story is this: if I am not logged on my site, then I can open my site number of tabs and browsers. But as soon as I logged in my site, I am getting the error above.

 <authentication mode="Forms">
  <forms name="MMFormAUTH" loginUrl="Pages/LandingPage.aspx" defaultUrl="Pages/LandingPage.aspx" timeout="60" protection="All" slidingExpiration="true" enableCrossAppRedirects="false" requireSSL="false" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>
<sessionState cookieless="false" cookieName="abc" mode="InProc" timeout="60">
</sessionState>
<httpRuntime maxRequestLength="1000240" executionTimeout="120" />


问:
Create TestNg Xml file programmatically using Java
I have a following testNg xml file.

Can someone please advice how to create this dynamically using java.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <groups>
     <run>
       <include name="PrometheusHome" />
       <include name="AlertMgrHome" />
     </run>
   </groups>
    <classes>
      <class name="com.amex.eag.telemetry.testcases.PrometheusTests"/>
      <class name="com.amex.eag.telemetry.testcases.AlertManagerTests"/>
    </classes>
  </test>
</suite>
</code>```

答:
Adjusted core from here:</p>

```<code> public class DynamicTestNG {
 public void runTestNGTest(Map<String,String> testngParams)
 {   //Create an instance on TestNG
     TestNG myTestNG = new TestNG();

     //Create an instance of XML Suite and assign a name for it.
      XmlSuite mySuite = new XmlSuite();
      mySuite.setName("Suite");
      mySuite.setParallel(XmlSuite.ParallelMode.METHODS);

     //Create an instance of XmlTest and assign a name for it.
     XmlTest myTest = new XmlTest(mySuite);
     myTest.setName("Test");
     //add groups
     myTest.addIncludedGroup("PrometheusHome")
     myTest.addIncludedGroup("AlertMgrHome")

     //Add any parameters that you want to set to the Test.
     myTest.setParameters(testngParams);

     //Create a list which can contain the classes that you want to run.
     List<XmlClass> myClasses = new ArrayList<XmlClass>();
     myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.PrometheusTests"));
     myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.AlertManagerTests"));

     //Assign that to the XmlTest Object created earlier.
     myTest.setXmlClasses(myClasses);

     //Create a list of XmlTests and add the Xmltest you created earlier to it.
     List<XmlTest> myTests = new ArrayList<XmlTest>();
     myTests.add(myTest);

     //add the list of tests to your Suite.
     mySuite.setTests(myTests);

     //Add the suite to the list of suites.
     List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
     mySuites.add(mySuite);

     //Set the list of Suites to the testNG object you created earlier.
     myTestNG.setXmlSuites(mySuites);
     mySuite.setFileName("myTemp.xml");
     mySuite.setThreadCount(3);
     myTestNG.run();

     //Create physical XML file based on the virtual XML content
     for(XmlSuite suite : mySuites)
     {
         createXmlFile(suite);
     }
     System.out.println("File generated successfully.");

     //Print the parameter values
     Map<String,String> params = myTest.getParameters();
     for(Map.Entry<String, String> entry : params.entrySet())
     {
       System.out.println(entry.getKey() + " => " + entry.getValue());
     }
    }
    //This method will create an Xml file based on the XmlSuite data
    public void createXmlFile(XmlSuite mSuite)
    {
       FileWriter writer;
       try {
            writer = new FileWriter(new File("myTemp.xml"));
            writer.write(mSuite.toXml());
            writer.flush();
            writer.close();
            System.out.println(new File("myTemp.xml").getAbsolutePath());
           } catch (IOException e)
            {
              e.printStackTrace();
            }
    }
   //Main Method
   public static void main (String args[])
   {
      DynamicTestNG dt = new DynamicTestNG();
      //This Map can hold your testng Parameters.
      Map<String,String> testngParams = new HashMap<String,String> ();
      testngParams.put("device1", "Desktop");
      dt.runTestNGTest(testngParams);
   }
 }
</code>```

Body:
I have a following testNg xml file.

Can someone please advice how to create this dynamically using java.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <groups>
     <run>
       <include name="PrometheusHome" />
       <include name="AlertMgrHome" />
     </run>
   </groups>
    <classes>
      <class name="com.amex.eag.telemetry.testcases.PrometheusTests"/>
      <class name="com.amex.eag.telemetry.testcases.AlertManagerTests"/>
    </classes>
  </test>
</suite>

Body:
Adjusted core from here:

 public class DynamicTestNG {
 public void runTestNGTest(Map<String,String> testngParams)
 {   //Create an instance on TestNG
     TestNG myTestNG = new TestNG();

     //Create an instance of XML Suite and assign a name for it.
      XmlSuite mySuite = new XmlSuite();
      mySuite.setName("Suite");
      mySuite.setParallel(XmlSuite.ParallelMode.METHODS);

     //Create an instance of XmlTest and assign a name for it.
     XmlTest myTest = new XmlTest(mySuite);
     myTest.setName("Test");
     //add groups
     myTest.addIncludedGroup("PrometheusHome")
     myTest.addIncludedGroup("AlertMgrHome")

     //Add any parameters that you want to set to the Test.
     myTest.setParameters(testngParams);

     //Create a list which can contain the classes that you want to run.
     List<XmlClass> myClasses = new ArrayList<XmlClass>();
     myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.PrometheusTests"));
     myClasses.add(new XmlClass("com.amex.eag.telemetry.testcases.AlertManagerTests"));

     //Assign that to the XmlTest Object created earlier.
     myTest.setXmlClasses(myClasses);

     //Create a list of XmlTests and add the Xmltest you created earlier to it.
     List<XmlTest> myTests = new ArrayList<XmlTest>();
     myTests.add(myTest);

     //add the list of tests to your Suite.
     mySuite.setTests(myTests);

     //Add the suite to the list of suites.
     List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
     mySuites.add(mySuite);

     //Set the list of Suites to the testNG object you created earlier.
     myTestNG.setXmlSuites(mySuites);
     mySuite.setFileName("myTemp.xml");
     mySuite.setThreadCount(3);
     myTestNG.run();

     //Create physical XML file based on the virtual XML content
     for(XmlSuite suite : mySuites)
     {
         createXmlFile(suite);
     }
     System.out.println("File generated successfully.");

     //Print the parameter values
     Map<String,String> params = myTest.getParameters();
     for(Map.Entry<String, String> entry : params.entrySet())
     {
       System.out.println(entry.getKey() + " => " + entry.getValue());
     }
    }
    //This method will create an Xml file based on the XmlSuite data
    public void createXmlFile(XmlSuite mSuite)
    {
       FileWriter writer;
       try {
            writer = new FileWriter(new File("myTemp.xml"));
            writer.write(mSuite.toXml());
            writer.flush();
            writer.close();
            System.out.println(new File("myTemp.xml").getAbsolutePath());
           } catch (IOException e)
            {
              e.printStackTrace();
            }
    }
   //Main Method
   public static void main (String args[])
   {
      DynamicTestNG dt = new DynamicTestNG();
      //This Map can hold your testng Parameters.
      Map<String,String> testngParams = new HashMap<String,String> ();
      testngParams.put("device1", "Desktop");
      dt.runTestNGTest(testngParams);
   }
 }


问:
Multiple relations from many entities to one entitiy in SQL Server (EF core)
Can anybody help me? I want to set constraint to my database for example:

First entity is Triangle (Triangle_Id, Name, Side_size)

Second entity is Square (Square_Id, Name, Side_size)

Third entity is Area (Area_Id, ObjectId, Area_value)

Fourth entity is Circle (Circle_Id, Name, Radius)

How can I add constraints from entities Triangle and Square to Area that I am unable to write any other type of objects in ObjectId column except triangle or square?

I tried to write come FK constraints, but have had an error.

FK_Area_Triangle_ObjectId (area_ObjectId == triangle_Id)

FK_Area_Square_ObjectId (area_ObjectId == square_Id)

答:
You cannot have two different foreign key constraints on same column, but there are some options as answered here: Foreign Key to multiple tables.

You could simply create two columns in Area, SquareId and TriangleId, and have nullable Foreign Keys to each table. You can also add a constraint, that exactly one of these two columns has to be filled.

Model an entity that acts as a base for both Square and Triangle, and have Area refer to that entity


问:
How can I Hash hundred thousand records taken as a input from CSV file?
By using this code I'm able to hash only 1 record without any errors or warnings. How can I hash a hundred thousand records taken as input from the CSV file?

```<code>import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)
proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]
        proper[order_id] = country
#print(proper)
def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100
get_hash('503618705')

class HashTable:
    def __init__(self):
        self.MAX = 100
        self.arr = [None for i in range(self.MAX)]

    def get_hash(self, key):
        key = int(key, base=10)
        hash_key = 0
        for i in range(key):
            hash_key += 1
        return hash_key % self.MAX

    def __getitem__(self, index):
        h = self.get_hash(index)
        return self.arr[h]

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        self.arr[h] = val

    def __delitem__(self, key):
        h = self.get_hash(key)
        self.arr[h] = None
t = HashTable()
t["503618705"] = "Tanzania"
t.arr
print(t.arr)
</code>```

The code is free of errors but I want to hash all the records in the CSV File

答:
What you need to do, is acctually use your methods.
right now you __init__ a new object t. Then you are refering to a index in your list and set "Tanzania" as value. så you actually dont use your methods in your object t only the function list, so what you can do is (I hope I understanded your question correctly.):

```<code>lst = ['Sweden', 'Germany', 'Pakistan', 'Syria', 'Norway']
idx = ["1234", "30", "500", "2034", "443"]

def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100
get_hash('50')

class HashTable:
    def __init__(self):
        self.MAX = 100
        self.arr = [None for i in range(self.MAX)]

    def get_hash(self, key):
        key = int(key, base=10)
        hash_key = 0
        for i in range(key):
            hash_key += 1
        return hash_key % self.MAX

    def __getitem__(self, index):
        h = self.get_hash(index)
        return self.arr[h]

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        self.arr[h] = val

    def __delitem__(self, key):
        h = self.get_hash(key)
        self.arr[h] = None
t = HashTable()
for n, i in enumerate(lst):
    t.__setitem__(idx[n], lst[n])
for i in range(len(idx)):
    print(t.__getitem__(idx[i]))
    print(t.get_hash(idx[i]))
</code>```

Body:
By using this code I'm able to hash only 1 record without any errors or warnings. How can I hash a hundred thousand records taken as input from the CSV file?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)
proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]
        proper[order_id] = country
#print(proper)
def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100
get_hash('503618705')

class HashTable:
    def __init__(self):
        self.MAX = 100
        self.arr = [None for i in range(self.MAX)]

    def get_hash(self, key):
        key = int(key, base=10)
        hash_key = 0
        for i in range(key):
            hash_key += 1
        return hash_key % self.MAX

    def __getitem__(self, index):
        h = self.get_hash(index)
        return self.arr[h]

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        self.arr[h] = val

    def __delitem__(self, key):
        h = self.get_hash(key)
        self.arr[h] = None
t = HashTable()
t["503618705"] = "Tanzania"
t.arr
print(t.arr)

The code is free of errors but I want to hash all the records in the CSV File

Body:
What you need to do, is acctually use your methods.
right now you __init__ a new object t. Then you are refering to a index in your list and set "Tanzania" as value. så you actually dont use your methods in your object t only the function list, so what you can do is (I hope I understanded your question correctly.):

lst = ['Sweden', 'Germany', 'Pakistan', 'Syria', 'Norway']
idx = ["1234", "30", "500", "2034", "443"]

def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100
get_hash('50')

class HashTable:
    def __init__(self):
        self.MAX = 100
        self.arr = [None for i in range(self.MAX)]

    def get_hash(self, key):
        key = int(key, base=10)
        hash_key = 0
        for i in range(key):
            hash_key += 1
        return hash_key % self.MAX

    def __getitem__(self, index):
        h = self.get_hash(index)
        return self.arr[h]

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        self.arr[h] = val

    def __delitem__(self, key):
        h = self.get_hash(key)
        self.arr[h] = None
t = HashTable()
for n, i in enumerate(lst):
    t.__setitem__(idx[n], lst[n])
for i in range(len(idx)):
    print(t.__getitem__(idx[i]))
    print(t.get_hash(idx[i]))


问:
How do I atomically increment a variable in Swift?
I want to be able to increment a counter atomically and I can't find any reference on how to do it.

Adding more information based on comments:

Are you using GCD? No. I am not using GCD. Having to use a queue system to increment a number seems overkill.

Do You understand basic thread safety? Yes I do otherwise I would not be asking about atomic increments.

Is this variable local? No.

Is it instance level? Yes it should be part of a single instance.

I want to do  something like this:

```<code> class Counter {
      private var mux: Mutex
      private (set) value: Int
      func increment() {
          mux.lock()
          value += 1
          mux.unlock()
      }
 }
</code>```

答:
There are various approaches we can use to have atomically increment a variable in swift and has been discussed here.

Also there is a swift proposal SE-0283 to add atomic variables natively in swift.

Body:
I want to be able to increment a counter atomically and I can't find any reference on how to do it.

Adding more information based on comments:

Are you using GCD? No. I am not using GCD. Having to use a queue system to increment a number seems overkill.

Do You understand basic thread safety? Yes I do otherwise I would not be asking about atomic increments.

Is this variable local? No.

Is it instance level? Yes it should be part of a single instance.

I want to do  something like this:

 class Counter {
      private var mux: Mutex
      private (set) value: Int
      func increment() {
          mux.lock()
          value += 1
          mux.unlock()
      }
 }


问:
GlobalKTable Refresh Logic
When there are updates done to an underlying topic of a GlobalKTable, what is the logic for all instances of KStream apps to get the latest data? Below are my follow up questions:

Would the GlobalKTable be locked at record level or table level when the updates are happening?

According to this blog: Kafka GlobalKTable Latency Issue, can the latency go upto 0.5s?! If so, is there any alternative to reduce the latency?

Since GlobalKTable uses RocksDB by default as the state store, are all features of RocksDB available to use?

I understand the GlobalKTable should not be used for use-cases that require frequent updates to the lookup data. Is there any other key-value store that we can use for use-cases that might require updates on table data - Redis for example?

I could not find much documentation about GlobalKTable and its internals. Is there any available documentations available?

答:
The Javadocs for KStream#join() are pretty clear that joins against a GlobalKTable only occur as records in the stream are processed.  Therefore, to answer your question, there are no automatic updates that happen to the underlying KStreams: new messages would need to be processed in them in order for them to see the updates.

"Table lookup join" means, that results are only computed if KStream
  records are processed.  This is done by performing a lookup for
  matching records in the current internal GlobalKTable state.  In
  contrast, processing GlobalKTable input records will only update the
  internal GlobalKTable state and will not produce any result records.

If a GlobalKTable is materialized as a key-value store, most of the methods for iterating over and mutating KeyValueStore implementations use the synchronized keyword to prevent interference from multiple threads updating the state store concurrently.

You might be able to reduce the latency by using an in-memory key-value store, or by using a custom state store implementation.

Interacting with state stores is controlled via a set of interfaces in Kafka Streams, for example KeyValueStore, so in this sense you're not interacting directly with RocksDB APIs.

Title: GlobalKTable Refresh Logic


问:
Form Recognizer Api | Fix from 11.05.2020 | Client Prases results with null fields
Is there an updated NuGet package for the latest Fix from the 11-05-2020 available? We basically need the latest fixes from the Azure.AI.Formrecognizer 1.0.0-preview.3 version.

Regarding this Post:

https://github.com/Azure/azure-sdk-for-net/commit/904cfe1cb490047ffb622843afb385b4dd1dff12#diff-16e8103b54629d7b864160cc0edd0bde

Since I very much need this NuGet package in order to continue my development, I would be more than happy if I could install one as soon as possible.

答:
Please find here the latest SDKs releases docs, these SDKs support the Form Recognizer v2.0 release:

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/client-library?tabs=windows&pivots=programming-language-csharp


问:
How to get content on the right of a card to position under the image using bootstrap?
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

```<code>    <div class="card">
        <div class="row no-gutters">
           <div class="col-auto col-md-6">
               <img src="img/image.jpg" class="img-fluid image" alt="PayCloud App Demo" width="620" height="465">
           </div>
           <div class="col">
             <div class="card-block px-2">
                <p class="card-title AppName">AppName</p>
                <p class="card-title Description">Restaurant Payment Service - January 2020</p>
                <p class="card-text AppDescription">App Description.</p>
                <a href="link.html"><span class="button">View Project</span></a>
             </div>
          </div>
       </div>
</div>
</code>```

CSS Below

```<code>.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}
</code>```

答:
I fixed it by changing "col" to "col-auto" and also adding "col-md-6" in the class

Code Below

```<code><div class="card">
        <div class="row no-gutters">
           <div class="col-auto col-md-6">
               <img src="img/image.jpg" class="img-fluid image" alt="PayCloud App Demo" width="620" height="465">
           </div>
           <div class="col-auto col-md-6">
             <div class="card-block px-2">
                <p class="card-title AppName">AppName</p>
                <p class="card-title Description">Restaurant Payment Service - January 2020</p>
                <p class="card-text AppDescription">App Description.</p>
                <a href="link.html"><span class="button">View Project</span></a>
             </div>
          </div>
       </div>
</div>
</code>```

Body:
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

AppName

Restaurant Payment Service - January 2020

App Description.

                View Project

CSS Below

.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}

Body:
I fixed it by changing "col" to "col-auto" and also adding "col-md-6" in the class

Code Below

<div class="card">
        <div class="row no-gutters">
           <div class="col-auto col-md-6">
               <img src="img/image.jpg" class="img-fluid image" alt="PayCloud App Demo" width="620" height="465">
           </div>
           <div class="col-auto col-md-6">
             <div class="card-block px-2">
                <p class="card-title AppName">AppName</p>
                <p class="card-title Description">Restaurant Payment Service - January 2020</p>
                <p class="card-text AppDescription">App Description.</p>
                <a href="link.html"><span class="button">View Project</span></a>
             </div>
          </div>
       </div>
</div>


问:
Postgresql | How to attribute index updation time in Sql Inserts
How can we attribute time taken in index updation process while executing an insert statement in postgresql?</p>

答:
You will not get that information through explain. The best way is to run this in a loop using a script or pgbench with the index absent and then remove the data and repeat with the index present.

Just remember to VACUUM ANALYSE the table before each test. If you can close the table consider VACUUM FULL or CLUSTER.

Remember that the times may be different depending on the size of the table and the index, state of the table and the index and index level of complexity. So the result will be different if you insert into an empty table and if you insert into a table with 100M rows.


问:
How to filter myself out of Google Analytics with a dynamic IP address?
Does anyone know how to setup Google Analytics to filter yourself out if you're visiting the site from a dynamic IP address?  I don't want to include myself in my stats from home use where I have a dynamic IP address via Verizon FiOS.</p>

答:
You can do this by creating a special page on your site that sets a Google Analytics segmentation cookie, using code something like:

```<code><body onLoad="javascript:__utmSetVar('exclude_from_report')">
</code>```

Then create a custom filter in Analytics to exclude visitors that match the 'exclude_from_report' segment pattern.

OwnerDisplayName: magenta

ContentLicense: CC BY-SA 2.5

Body:
You can do this by creating a special page on your site that sets a Google Analytics segmentation cookie, using code something like:

<body onLoad="javascript:__utmSetVar('exclude_from_report')">

Then create a custom filter in Analytics to exclude visitors that match the 'exclude_from_report' segment pattern.

OwnerDisplayName: cxfx


问:
Tidying up my ASP.NET project has broken my relative paths
I have just created some directories and tidied up my growing ASP.NET project but it has caused some issues that I can't solve. I have a directory in the root of the project called js and another one called Pages.

In Pages I have a file called MasterPage.master which is a master page. The Pages directory has Default.aspx and some subdirectories of other pages.

I have two main issues. In MasterPage.master I have code like this to reference javascript files:

However none of my javascript can be found any more. I tried  and I tried  but it still doesn't work.

The other issue is that I have a menu system written is CSS and that has some strange behaviour. When the page loads the menu works fine. If I navigate to /Pages/Trades/TradeInfo.aspx and then hover over that item the page path now says /Pages/Trades/Trades/TradeInfo.aspx

Why has the Trades directory been added twice?

答:
Have you tried ResolveUrl?

It sure works for the script tags and your anchor tags.

```<code> <script src='<%=ResolveUrl("~/Scripts/jquery/ui/jquery-ui-1.8.11.custom.min.js") %>' type="text/javascript"></script>
</code>```

Body:
Have you tried ResolveUrl?

It sure works for the script tags and your anchor tags.

 <script src='<%=ResolveUrl("~/Scripts/jquery/ui/jquery-ui-1.8.11.custom.min.js") %>' type="text/javascript"></script>


问:
Multiple options menu showing up on app bar
Let me add more context:

I run bottom view navigation with a ViewPager2. For all 4 of my tab/fragments of my bottom navigation view I have an options menu which I created separately dynamically in each fragment.

Now, when we navigate through the app, it behaves correctly as every options menu is displayed ONLY for their respective fragment.

Problem is: Only when the app is launched, all the options menus from all the the 4 fragments show up on the start destination fragment's tab. BUT, once we swipe and swipe back, only the start destinations options menu is shown on the app bar. As is for every of the other 3 fragment/tabs.

Theory: I think it has something to do with onCreateOptionsMenu which is called when all four fragments are also created to which they share an app bar.

Is anybody familiar with this type of issue? Here is my PagerAdapters code for my ViewPager:

```<code>const val F1_PAGE_INDEX = 0
const val F2_PAGE_INDEX = 1
const val F3_PAGE_INDEX = 2
const val F4_PAGE_INDEX = 3

class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {

    /**
     * Mapping of the ViewPager page indexes to their respective Fragments
     */
    private val tabFragmentsCreators: Map<Int, () -> Fragment> = mapOf(
        F1_PAGE_INDEX to { FirstFragment() },
        F2_PAGE_INDEX to { SecondFragment() },
        F3_PAGE_INDEX to { ThirdFragment() },
        F4_PAGE_INDEX to { FourthFragment() }
    )

    override fun getItemCount() = tabFragmentsCreators.size

    override fun createFragment(position: Int): Fragment {
        return tabFragmentsCreators[position]?.invoke() ?: throw IndexOutOfBoundsException()
    }

}
</code>```

Here is also my Home View Pager Fragment where I create my bottom Navigation and affect to to the main fragments:

```<code>class HomeViewPagerFragment(): Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding = FragmentViewPagerBinding.inflate(inflater, container, false)

        val viewPager = binding.viewPager

        viewPager.isUserInputEnabled = false

        viewPager.adapter = PagerAdapter(this)

        //Save states of four fragments
        viewPager.offscreenPageLimit = 4

        (activity as AppCompatActivity).setSupportActionBar(binding.toolbar)

        val bottomNavigation = binding.bottomNavView

        bottomNavigation.setOnNavigationItemSelectedListener(
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.fragment1_destination -> viewPager.currentItem = F1_PAGE_INDEX
                    R.id.fragment2_destination -> viewPager.currentItem = F2_PAGE_INDEX
                    R.id.fragment3_destination -> viewPager.currentItem = F3_PAGE_INDEX
                    R.id.fragment4_destination -> viewPager.currentItem = F4_PAGE_INDEX
                }
                true
            })
        return binding.root
    }

}
</code>```

The starting destination (first fragment) is where all the fragment's menu are shown at app start.

Any kind of help is appreciated! Thank you!

答:
I think what you need to do is, make OptionsMenu visible only when that fragment is visible.

Try this: Put this in each fragment

```<code>override fun onResume(){
    super.onResume()
    setHasOptionsMenu(isVisible())
}
</code>```

This will make the options menu visible only when that fragment is visible. You can make it hidden in onCreateView or in onPause if just onResume doesn't work.

Body:
Let me add more context:

I run bottom view navigation with a ViewPager2. For all 4 of my tab/fragments of my bottom navigation view I have an options menu which I created separately dynamically in each fragment.

Now, when we navigate through the app, it behaves correctly as every options menu is displayed ONLY for their respective fragment.

Problem is: Only when the app is launched, all the options menus from all the the 4 fragments show up on the start destination fragment's tab. BUT, once we swipe and swipe back, only the start destinations options menu is shown on the app bar. As is for every of the other 3 fragment/tabs.

Theory: I think it has something to do with onCreateOptionsMenu which is called when all four fragments are also created to which they share an app bar.

Is anybody familiar with this type of issue? Here is my PagerAdapters code for my ViewPager:

const val F1_PAGE_INDEX = 0
const val F2_PAGE_INDEX = 1
const val F3_PAGE_INDEX = 2
const val F4_PAGE_INDEX = 3

class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {

    /**
     * Mapping of the ViewPager page indexes to their respective Fragments
     */
    private val tabFragmentsCreators: Map<Int, () -> Fragment> = mapOf(
        F1_PAGE_INDEX to { FirstFragment() },
        F2_PAGE_INDEX to { SecondFragment() },
        F3_PAGE_INDEX to { ThirdFragment() },
        F4_PAGE_INDEX to { FourthFragment() }
    )

    override fun getItemCount() = tabFragmentsCreators.size

    override fun createFragment(position: Int): Fragment {
        return tabFragmentsCreators[position]?.invoke() ?: throw IndexOutOfBoundsException()
    }

}

Here is also my Home View Pager Fragment where I create my bottom Navigation and affect to to the main fragments:

class HomeViewPagerFragment(): Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding = FragmentViewPagerBinding.inflate(inflater, container, false)

        val viewPager = binding.viewPager

        viewPager.isUserInputEnabled = false

        viewPager.adapter = PagerAdapter(this)

        //Save states of four fragments
        viewPager.offscreenPageLimit = 4

        (activity as AppCompatActivity).setSupportActionBar(binding.toolbar)

        val bottomNavigation = binding.bottomNavView

        bottomNavigation.setOnNavigationItemSelectedListener(
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.fragment1_destination -> viewPager.currentItem = F1_PAGE_INDEX
                    R.id.fragment2_destination -> viewPager.currentItem = F2_PAGE_INDEX
                    R.id.fragment3_destination -> viewPager.currentItem = F3_PAGE_INDEX
                    R.id.fragment4_destination -> viewPager.currentItem = F4_PAGE_INDEX
                }
                true
            })
        return binding.root
    }

}

The starting destination (first fragment) is where all the fragment's menu are shown at app start.

Any kind of help is appreciated! Thank you!

Body:
I think what you need to do is, make OptionsMenu visible only when that fragment is visible.

Try this: Put this in each fragment

override fun onResume(){
    super.onResume()
    setHasOptionsMenu(isVisible())
}

This will make the options menu visible only when that fragment is visible. You can make it hidden in onCreateView or in onPause if just onResume doesn't work.